我有一个新的行字符字符串。我想把这个字符串转换成一个数组,对于每一个新行,在数组中跳转一个索引位置。
如果字符串是:
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
)
当前回答
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>
其他回答
您可以执行$string = nl2br($string),以便将换行符更改为
<br />.
这样,系统使用\r\n或\n或\r就无关紧要了
然后你可以把它输入一个数组:
$array = explode("<br />", $string);
大卫有一个伟大的方向,但它错过了\r。这招对我很管用:
$array = preg_split("/(\r\n|\n|\r)/", $string);
我一直都很成功地使用这个方法:
$array = preg_split("/\r\n|\n|\r/", $string);
(更新为最后的\r,谢谢@LobsterMan)
只使用'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)
这个方法对我来说总是有效的:
$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'])));