我有一个新的行字符字符串。我想把这个字符串转换成一个数组,对于每一个新行,在数组中跳转一个索引位置。
如果字符串是:
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
)
当前回答
您可以执行$string = nl2br($string),以便将换行符更改为
<br />.
这样,系统使用\r\n或\n或\r就无关紧要了
然后你可以把它输入一个数组:
$array = explode("<br />", $string);
其他回答
<anti-answer>
正如其他答案所指定的,一定要使用爆炸而不是分裂,因为从PHP 5.3.0开始,分裂已被弃用。例如,以下不是你想要的方式:
$your_array = split(chr(10), $your_string);
LF = "\n" = chr(10), CR = "\r" = chr(13)
</anti-answer>
我在PHP文档中找到了这个:
<?php
// Split the phrase by any number of commas or space characters,
// which include " ", \r, \t, \n and \f
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
print_r($keywords);
?>
您可以执行$string = nl2br($string),以便将换行符更改为
<br />.
这样,系统使用\r\n或\n或\r就无关紧要了
然后你可以把它输入一个数组:
$array = explode("<br />", $string);
大卫有一个伟大的方向,但它错过了\r。这招对我很管用:
$array = preg_split("/(\r\n|\n|\r)/", $string);
你可以用这个:
\str_getcsv($str, PHP_EOL);