php 如何将字符串放入数组中,由新行拆分?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1483497/
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
How can I put strings in an array, split by new line?
提问by Johan
I have a string with line breaks in my database. I want to convert that string into an array, and for every new line, jump one index place in the array.
我的数据库中有一个带换行符的字符串。我想将该字符串转换为数组,并且对于每一个新行,在数组中跳转一个索引位置。
If the string is:
如果字符串是:
My text1
My text2
My text3
The result I want is this:
我想要的结果是这样的:
Array
(
[0] => My text1
[1] => My text2
[2] => My text3
)
回答by David
I've always used this with great success:
我一直都非常成功地使用它:
$array = preg_split("/\r\n|\n|\r/", $string);
(updated with the final \r, thanks @LobsterMan)
(用最后的 \r 更新,谢谢@LobsterMan)
回答by Pascal MARTIN
You can use the explodefunction, using "\n" as separator:
您可以使用该explode函数,使用“ \n”作为分隔符:
$your_array = explode("\n", $your_string_from_db);
For instance, if you have this piece of code:
例如,如果你有这段代码:
$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);
var_dump($arr);
You'd get this output:
你会得到这个输出:
array
0 => string 'My text1' (length=8)
1 => string 'My text2' (length=8)
2 => string 'My text3' (length=8)
Note that you have to use a double-quoted string, so \nis actually interpreted as a line-break.
(See that manual page for more details.)
请注意,您必须使用双引号 string,因此\n实际上被解释为换行符。
(有关更多详细信息,请参阅该手册页。)
回答by hesselbom
A line break is defined differently on different platforms, \r\n, \r or \n.
换行符在不同平台上的定义不同,\r\n、\r 或\n。
Using RegExp to split the string you can match all three with \R
使用 RegExp 拆分字符串,您可以将所有三个与 \R 匹配
So for your problem:
所以对于你的问题:
$array = preg_split ('/$\R?^/m', $string);
That would match line breaks on Windows, Mac and Linux!
这将匹配 Windows、Mac 和 Linux 上的换行符!
回答by voidstate
PHP already knows the current system's newline character(s). Just use the EOL constant.
PHP 已经知道当前系统的换行符。只需使用 EOL 常量。
explode(PHP_EOL,$string)
回答by Reed
An alternative to Davids answerwhich is faster (way faster) is to use str_replaceand explode.
更快(更快)的Davids 答案的替代方法是使用str_replaceand explode。
$arrayOfLines = explode("\n",
str_replace(["\r\n","\n\r","\r"],"\n",$str)
);
What's happening is:
Since line breaks can come in different forms, I str_replace\r\n, \n\r, and \r with \n instead (and original \n are preserved).
Then explode on \nand you have all the lines in an array.
发生的事情是:
由于换行符可以以不同的形式出现,所以我用str_replace\r\n、\n\r 和 \r 代替(并且保留了原始的 \n)。
然后爆炸\n,你有一个数组中的所有行。
I did a benchmark on the src of this page and split the lines 1000 times in a for loop and:preg_replacetook an avg of 11 secondsstr_replace & explodetook an avg of about 1 second
我在这个页面的 src 上做了一个基准测试,并在 for 循环中将行拆分 1000 次,并且:preg_replace平均花费了 11 秒str_replace & explode,平均花费了大约 1 秒
More detail and bencmark info on my forum
在我的论坛上有更多详细信息和基准信息
回答by LobsterMan
David: Great direction, but you missed \r. this worked for me:
大卫:伟大的方向,但你错过了\r。这对我有用:
$array = preg_split("/(\r\n|\n|\r)/", $string);
回答by Spooky
You don't need preg_* functions nor preg patterns nor str_replace within, etc .. in order to sucessfuly break a string into array by newlines. In all scenarios, be it Linux/Mac or m$, this will do.
您不需要 preg_* 函数,也不需要 preg 模式,也不需要 str_replace 内等..以便通过换行符成功地将字符串分解为数组。在所有情况下,无论是 Linux/Mac 还是 m$,这都行。
<?php
$array = explode(PHP_EOL, $string);
// ...
$string = implode(PHP_EOL, $array);
?>
PHP_EOLis a constant holding the line break character(s) used by the server platform.
PHP_EOL是一个常量,用于保存服务器平台使用的换行符。
回答by Deen Foxx
StackOverflow will not allow me to comment on hesselbom's answer (not enough reputation), so I'm adding my own...
StackOverflow 不允许我对 hesselbom 的回答发表评论(没有足够的声誉),所以我正在添加我自己的......
$array = preg_split('/\s*\R\s*/', trim($text), NULL, PREG_SPLIT_NO_EMPTY);
This worked best for me because it also eliminates leading (second \s*) and trailing (first \s*) whitespace automatically and also skips blank lines (the PREG_SPLIT_NO_EMPTY flag).
这对我来说效果最好,因为它还会自动消除前导(第二个 \s*)和尾随(第一个 \s*)空格并跳过空行(PREG_SPLIT_NO_EMPTY 标志)。
-= OPTIONS =-
-= 选项 =-
If you want to keep leading whitespace, simply get rid of the second \s* and make it an rtrim() instead...
如果你想保持领先的空格,只需去掉第二个 \s* 并将其改为 rtrim() ......
$array = preg_split('/\s*\R/', rtrim($text), NULL, PREG_SPLIT_NO_EMPTY);
If you need to keep empty lines, get rid of the NULL (it is only a placeholder) and PREG_SPLIT_NO_EMPTY flag, like so...
如果你需要保留空行,去掉 NULL(它只是一个占位符)和 PREG_SPLIT_NO_EMPTY 标志,就像这样......
$array = preg_split('/\s*\R\s*/', trim($text));
Or keeping both leading whitespace and empty lines...
或者同时保留前导空格和空行...
$array = preg_split('/\s*\R/', rtrim($text));
I don't see any reason why you'd ever want to keep trailing whitespace, so I suggest leaving the first \s* in there. But, if all you want is to split by new line (as the title suggests), it is THIS simple (as mentioned by Jan Goyvaerts)...
我看不出有任何理由让您想要继续尾随空格,所以我建议将第一个 \s* 留在那里。但是,如果您只想按新行拆分(如标题所示),那就很简单(如 Jan Goyvaerts 所述)...
$array = preg_split('/\R/', $text);
回答by Damien MATHIEU
explode("\n", $str);
The " (instead of ') is quite important as otherwise, the line break wouln't get interpreted.
"(而不是 ')非常重要,否则不会解释换行符。
回答by Tom
<anti-answer>
As other answers have specified, be sure to use exploderather than splitbecause as of PHP 5.3.0 splitis deprecated. i.e. the following is NOTthe way you want to do it:
正如其他答案所指定的那样,请务必使用explode而不是split因为 PHP 5.3.0split已被弃用。即以下不是您想要的方式:
$your_array = split(chr(10), $your_string);
LF = "\n" = chr(10), CR = "\r" = chr(13)
LF = "\n" = chr(10), CR = "\r" = chr(13)
</anti-answer>

