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

如果字符串是:

My text1
My text2
My text3

我想要的结果是:

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

当前回答

我在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);
?>

其他回答

只使用'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)

PHP已经知道当前系统的换行符。只用EOL常数。

explode(PHP_EOL,$string)

对于任何试图在crontab中显示cronjob并且不知道如何分隔每行的人,请使用爆炸:

$output = shell_exec('crontab -l');
$cron_array = explode(chr(10),$output);

使用'\n'似乎不工作,但chr(10)工作得很好:D

希望这能让一些人少头疼。

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秒

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

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

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

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