天天看點

php處理檔案的思考(去除空行、每行多餘字元)

1.去除空行

<?php
$str = file_get_contents('a.txt');
$str = explode(PHP_EOL, $str);    //分割為數組,每行為一個數組元素
$str = array_filter($str);    //去除數組中的空元素
$str = implode(PHP_EOL,$str);    //用換行符連結數組為字元串
file_put_contents('b.txt',$str);      

2.去除每行多餘字元

方式一,數組處理

<?php
$str = file_get_contents('a.txt');
$arr = explode(PHP_EOL,$str);
$result = array();
foreach($arr as $v)
{
    $result[] = trim(substr($v,6));
}
$result = array_filter($result);
$text = '';
foreach($result as $v)
{
    $text .= $v.PHP_EOL;
}
file_put_contents('b.txt',$text);
?>      

方式二,正則直接替換

<?php
$str = file_get_contents('a.txt');
$result = preg_replace('/\d+\.\s+/','',$str);
file_put_contents('c.txt',$result);
?>