我有一个新的行字符字符串。我想把这个字符串转换成一个数组,对于每一个新行,在数组中跳转一个索引位置。

如果字符串是:

My text1
My text2
My text3

我想要的结果是:

Array
(
    [0] => My text1
    [1] => My text2
    [2] => My text3
)

当前回答

你不需要preg_*函数、preg模式、str_replace within等,就可以通过换行成功地将字符串分解为数组。在所有场景中,无论是Linux、Mac还是Windows,这都可以。

<?php
    $array = explode(PHP_EOL, $string);
    // ...
    $string = implode(PHP_EOL, $array);
?>

PHP_EOL是一个常量,保存服务器平台使用的换行符。

其他回答

使用: $数组= preg_split (' / \ s * \ R \ s * /”,削减(文本)美元,NULL, PREG_SPLIT_NO_EMPTY);

这对我来说效果最好,因为它还自动消除了前导(第二个\s*)和尾导(第一个\s*)空白,还跳过空行(PREG_SPLIT_NO_EMPTY标志)。

选项

如果你想保留前导空白,只需去掉第二个\s*,改为rtrim()…

$array = preg_split('/\s*\R/', rtrim($text), NULL, PREG_SPLIT_NO_EMPTY);

如果你需要保留空行,去掉NULL(它只是一个占位符)和PREG_SPLIT_NO_EMPTY标志,就像这样…

$array = preg_split('/\s*\R\s*/', trim($text));

或者同时保留前导空格和空行……

$array = preg_split('/\s*\R/', rtrim($text));

我看不出有什么理由你会想要保留后面的空格,所以我建议把第一个\s*留在那里。但是,如果你想要的只是按新行分割(正如标题所暗示的那样),就是这么简单(正如Jan Goyvaerts所提到的)…

$array = preg_split('/\R/', $text);
explode("\n", $str);

"(而不是')非常重要,否则换行符不会被解释。

这个页面上有很多直接或间接的答案,评论中也有一些很好的建议,但没有一个答案能代表我在自己的项目中所写的内容。

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.

我一直都很成功地使用这个方法:

$array = preg_split("/\r\n|\n|\r/", $string);

(更新为最后的\r,谢谢@LobsterMan)

你可以使用爆炸函数,使用“\n”作为分隔符:

$your_array = explode("\n", $your_string_from_db);

例如,如果你有这样一段代码:

$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);
var_dump($arr);

你会得到这样的输出:

array
  0 => string 'My text1' (length=8)
  1 => string 'My text2' (length=8)
  2 => string 'My text3' (length=8)

注意,必须使用双引号字符串,因此\n实际上被解释为换行符。 (详情请参阅手册页。)