php 从文本文件中删除空行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17137286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove blank lines from a text file
提问by JayGatz
I have a text file that has some blank lines in it. Meaning lines that have nothing on them and are just taking up space.
我有一个文本文件,里面有一些空行。意思是上面没有任何东西并且只占用空间的线条。
It looks like this:
它看起来像这样:
The
quick
brown
fox jumped over
the
lazy dog
and I need it to look like this:
我需要它看起来像这样:
The
quick
brown
fox jumped over
the
lazy dog
How can I remove those blank lines and take only the lines with the content and write them to a new file?
如何删除那些空行并仅获取包含内容的行并将它们写入新文件?
Here is what I know how to do:
这是我知道该怎么做:
$file = fopen('newFile.txt', 'w');
$lines = fopen('tagged.txt');
foreach($lines as $line){
/* check contents of $line. If it is nothing or just a \n then ignore it.
else, then write it using fwrite($file, $line."\n");*/
}
回答by JRL
If the file is not too large:
如果文件不是太大:
file_put_contents('newFile.txt',
implode('', file('tagged.txt', FILE_SKIP_EMPTY_LINES)));
回答by gronostaj
Here's a foreach-based solution to just filter out empty lines (without writing to a file):
这是一个基于 foreach 的解决方案,用于过滤掉空行(不写入文件):
$lines = file('in.txt');
foreach ($lines as $k => $v) {
if (!trim($v))
unset($lines[$k]);
}
回答by CodeAngry
file_put_contents('newFile.txt',
preg_replace(
'~[\r\n]+~',
"\r\n",
trim(file_get_contents('tagged.txt'))
)
);
I like \r\n
:)
我喜欢\r\n
:)
回答by Maerlyn
file_put_contents(
"new_file.txt",
implode(
"",
array_filter(
file("old_file.txt")
))
);
This code first reads the file to an array (file()
), filters out the empty elements (array_filter
) then writes them to a new file. The implode delimiter is empty, as file
leaves the \n
characters at the end of each line.
此代码首先将文件读取到数组 ( file()
),过滤掉空元素 ( array_filter
),然后将它们写入新文件。内爆分隔符为空,因为在每行末尾file
留下\n
字符。
回答by mzedeler
You can do the whole thing in one go:
你可以一次性完成整个事情:
file_put_contents('newFile.txt',
preg_replace(
'/\R+/',
"\n",
file_get_contents('tagged.txt')
)
);
回答by Cthulhu
foreach($lines as $line) {
if ($line!=='') $file.write($line);
}
回答by geryjuhasz
try with strpos. search for \n. if returned value is 0 you unset line
尝试使用 strpos。搜索\n。如果返回值为 0,则取消设置行