我有一个新的行字符字符串。我想把这个字符串转换成一个数组,对于每一个新行,在数组中跳转一个索引位置。
如果字符串是:
My text1
My text2
My text3
我想要的结果是:
Array
(
[0] => My text1
[1] => My text2
[2] => My text3
)
我有一个新的行字符字符串。我想把这个字符串转换成一个数组,对于每一个新行,在数组中跳转一个索引位置。
如果字符串是:
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);
?>
其他回答
你可以使用爆炸函数,使用“\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实际上被解释为换行符。 (详情请参阅手册页。)
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>
explode("\n", $str);
"(而不是')非常重要,否则换行符不会被解释。
PHP已经知道当前系统的换行符。只用EOL常数。
explode(PHP_EOL,$string)
这就是我的方式:
$lines = preg_split('/[\r\n]+/', $db_text, NULL, PREG_SPLIT_NO_EMPTY);
这也将跳过所有空行。