0

I have the following script that is supposed to loop through the contents of a file and remove all the empty lines then rewrite the file only without the empty lines. Without writing to the file, or in otherwords by just having it echo the line, it works flawlessly. However when I try to get it to write to a file it just erases all the content of the file. No errors are returned. I'm open to new ways of the script running so anyway to achieve what I'm looking for would be great. Thanks in advance.

error_reporting(E_ALL);
ini_set('display_errors', true);

$filenameindex = "somefile";
$filecont = file($filenameindex);
$fileindex = fopen($filenameindex, "w") or die("can't open file");
foreach($filecont as $line)
{
    if(strlen($line) > 0)
    {
        fwrite($fileindex,$line);    
    }
}  
fclose($fileindex);
4

2 回答 2

0

您可以通过使用 preg_replace 来做到这一点

$filename = "somefile.txt";
$str = file_get_contents($filename);
$str = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\r\n", $str);
file_put_contents($filename, $str);

笔记!为了在记事本中正确显示换行符,我使用了“\r\n”而不是“\n”

于 2013-07-09T23:26:19.343 回答
0

这不是一个严格的 php 解决方案,但如果您的唯一目标是删除空格,那么仅使用 UNIX怎么样sed

sed -i '/^$/d' /somewhere/somefile.txt

您可以在 PHP 中使用shell_exec()或反引号调用它。这也是假设您使用的是 UNIX 系统,但它会消除将文件加载到 PHP 的开销。

于 2013-07-09T23:29:59.050 回答