我有一个新的行字符字符串。我想把这个字符串转换成一个数组,对于每一个新行,在数组中跳转一个索引位置。
如果字符串是:
My text1
My text2
My text3
我想要的结果是:
Array
(
[0] => My text1
[1] => My text2
[2] => My text3
)
我有一个新的行字符字符串。我想把这个字符串转换成一个数组,对于每一个新行,在数组中跳转一个索引位置。
如果字符串是:
My text1
My text2
My text3
我想要的结果是:
Array
(
[0] => My text1
[1] => My text2
[2] => My text3
)
当前回答
你可以用这个:
\str_getcsv($str, PHP_EOL);
其他回答
<anti-answer>
正如其他答案所指定的,一定要使用爆炸而不是分裂,因为从PHP 5.3.0开始,分裂已被弃用。例如,以下不是你想要的方式:
$your_array = split(chr(10), $your_string);
LF = "\n" = chr(10), CR = "\r" = chr(13)
</anti-answer>
explode("\n", $str);
"(而不是')非常重要,否则换行符不会被解释。
david的答案的另一个更快(更快)的选择是使用str_replace和爆炸。
$arrayOfLines = explode("\n",
str_replace(["\r\n","\n\r","\r"],"\n",$str)
);
现在的情况是: 由于换行符可以有不同的形式,我将str_replace \r\n、\n\r和\r替换为\n(并且保留原来的\n)。 然后在\n处爆炸,你就得到了一个数组中的所有行。
我在本页的src上做了一个基准测试,并在for循环中将行分割1000次,并且: Preg_replace的平均用时为11秒 Str_replace & explosion平均耗时约1秒
更多的细节和基准信息在我的论坛
这个页面上有很多直接或间接的答案,评论中也有一些很好的建议,但没有一个答案能代表我在自己的项目中所写的内容。
PHP转义序列\R文档:https://www.php.net/manual/en/regexp.reference.escape.php#:~:text=line%20break,\ R \n
代码:(演示)
$string = '
My text1
My text2
My text3
';
var_export(
preg_split('/\R+/', $string, 0, PREG_SPLIT_NO_EMPTY)
);
输出:
array (
0 => 'My text1',
1 => 'My text2',
2 => 'My text3',
)
OP没有提到从行中删除水平空白字符,因此不期望在变量(系统不可知)新行上爆炸时删除\s或\h。
虽然PHP_EOL是明智的建议,但当换行序列来自另一个操作系统时,它缺乏适当地爆炸字符串的灵活性。
使用非正则表达式爆炸往往不太直接,因为它需要字符串准备。此外,如果有多余的空白线需要清除,爆炸后可能会有清理工作。
Using \R+ (one or more consecutive newline sequences) and the PREG_SPLIT_NO_EMPTY function flag will deliver a gap-less, indexed array in a single, concise function call. Some people have a bias against regular expressions, but this is a perfect case for why regex should be used. If performance is a concern for valid reasons (e.g. you are processing hundreds of thousands of points of data), then go ahead and invest in benchmarking and micro-optimization. Beyond that, just use this one-line of code so that your code is brief, robust, and direct.
您可以执行$string = nl2br($string),以便将换行符更改为
<br />.
这样,系统使用\r\n或\n或\r就无关紧要了
然后你可以把它输入一个数组:
$array = explode("<br />", $string);