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

如果字符串是:

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

其他回答

这个方法对我来说总是有效的:

$uniquepattern = "gd$#%@&~#" // Any set of characters which you don’t expect to be present in user input $_POST['text']. Better use at least 32 characters.
$textarray = explode($uniquepattern, str_replace("\r", "", str_replace("\n", $uniquepattern, $_POST['text'])));
explode("\n", $str);

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

这就是我的方式:

$lines = preg_split('/[\r\n]+/', $db_text, NULL, PREG_SPLIT_NO_EMPTY);

这也将跳过所有空行。

<anti-answer>

正如其他答案所指定的,一定要使用爆炸而不是分裂,因为从PHP 5.3.0开始,分裂已被弃用。例如,以下不是你想要的方式:

$your_array = split(chr(10), $your_string);

LF = "\n" = chr(10), CR = "\r" = chr(13)

</anti-answer>

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

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

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

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