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

如果字符串是:

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>

其他回答

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

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

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

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

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

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

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

这就是我的方式:

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

这也将跳过所有空行。

您可以执行$string = nl2br($string),以便将换行符更改为

<br />. 

这样,系统使用\r\n或\n或\r就无关紧要了

然后你可以把它输入一个数组:

$array = explode("<br />", $string);

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>