Home > Backend Development > PHP Tutorial > 请教怎么按空行来分割txt文件,

请教怎么按空行来分割txt文件,

WBOY
Release: 2016-06-23 13:42:44
Original
2034 people have browsed it

请教怎么按空行来分割txt文件,
比如txt文件 a.txt

内容如下:
啊啊啊啊
呃呃呃

111111
222222

嘎嘎嘎嘎
嘎嘎嘎

里面有空行,怎么按空行把它切割成一段段的字符串呢


回复讨论(解决方案)

$content = file_get_contents('./a.txt');
$rows = explode("\r\n", $content);

调用函数file即可.

如果是以空行来分割就要找两个换行(\r\n)了
$str='123
defsf

abc
1213

&*(
';
print_r(explode("\n\r",$str)); //相当于print_r(explode("\r\n\r\n",$str)); 
或者用正则
preg_match('/[^.]+?(?=\r\n\r\n)/',$str,$mat);
print_r($mat);

正则那个用preg_match_all,少写了

$s =<<< TXT啊啊啊啊呃呃呃111111222222嘎嘎嘎嘎嘎嘎嘎TXT;$a = preg_split("/([\r\n]+)\\1/", $s);print_r($a);
Copy after login
Copy after login
Array(    [0] => 啊啊啊啊呃呃呃    [1] => 111111222222    [2] => 嘎嘎嘎嘎嘎嘎嘎)
Copy after login
Copy after login

$s =<<< TXT啊啊啊啊呃呃呃111111222222嘎嘎嘎嘎嘎嘎嘎TXT;$a = preg_split("/([\r\n]+)\\1/", $s);print_r($a);
Copy after login
Copy after login
Array(    [0] => 啊啊啊啊呃呃呃    [1] => 111111222222    [2] => 嘎嘎嘎嘎嘎嘎嘎)
Copy after login
Copy after login


我测试这段代码的结果是
Array ( [0] => 啊啊啊啊 呃呃呃 111111 222222 嘎嘎嘎嘎 嘎嘎嘎 )
Copy after login
Copy after login

如果文件数据比较小可以考虑先将内容一次性读取出来,然后使用explode方法进行分割。
如果文件非常大,一次性加载必然造成内存占用过大,性能低下。这种情况可以考虑open文件之后,逐行读取,对行数据进行校验从而进行分割。

$content = file_get_contents('./a.txt');
$rows = explode("\r\n", $content);



这样是按照换行分割,而不是按照空格分割,这样的结果会输出
Array ( [0] => 啊啊啊啊 [1] => 呃呃呃 [2] => [3] => 111111 [4] => 222222 [5] => [6] => 嘎嘎嘎嘎 [7] => 嘎嘎嘎 [8] => )
Copy after login

按照3楼的朋友说的使用$rows = explode("\r\n\r\n", $content);
输出的结果为
Array ( [0] => 啊啊啊啊 呃呃呃 111111 222222 嘎嘎嘎嘎 嘎嘎嘎 )
Copy after login
Copy after login

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template