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

如果字符串是:

My text1
My text2
My text3

我想要的结果是:

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

当前回答

Use:

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

foreach ($arr as $line_num => $line) {
    echo "Line #<b>{$line_num}</b>: " . htmlspecialchars($line) . "<br />\n";
}

真正的数组:

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

$array = array();

foreach ($arr as $line) { // loop line by line and convert into array
    $array[] = $line;
};

print_r($array); // display all value

echo $array[1]; // display index 1

嵌入在线:

正文,html, iframe { 宽度:100%; 高度:100%; 溢出:隐藏; } <iframe src="https://ideone.com/vE1gst" ></iframe>

其他回答

使用: $数组= 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);

你可以用这个:

 \str_getcsv($str, PHP_EOL);

只使用'base'包也是简单情况下的解决方案:

> s <- "a\nb\rc\r\nd"
> l <- strsplit(s,"\r\n|\n|\r")
> l  # the whole list...
[[1]]
[1] "a" "b" "c" "d"
> l[[1]][1] # ... or individual elements
[1] "a"
> l[[1]][2]
[1] "b"
> fun <- function(x) c('Line content:', x) # handle as you wish
> lapply(unlist(l), fun)

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秒

更多的细节和基准信息在我的论坛

你可以使用爆炸函数,使用“\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实际上被解释为换行符。 (详情请参阅手册页。)