如何将字符串放入数组中,并用新行分隔? [英] How can I put strings in an array, split by new line?
本文介绍了如何将字符串放入数组中,并用新行分隔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据库中有一个带换行符的字符串.我想将该字符串转换为数组,然后对于每一行,在数组中跳一个索引位置.
I have a string with line breaks in my database. I want to convert that string into an array, and for every new line, jump one index place in the array.
如果字符串是:
My text1
My text2
My text3
我想要的结果是这样:
Array
(
[0] => My text1
[1] => My text2
[2] => My text3
)
推荐答案
您可以使用 explode
函数,使用"\n
"作为分隔符:
You can use the explode
function, using "\n
" as separator:
$your_array = explode("\n", $your_string_from_db);
例如,如果您有这段代码:
For instance, if you have this piece of code:
$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)
请注意,您必须使用 double-带引号的字符串,因此\n
实际上被解释为换行符.
(有关更多详细信息,请参见该手册页.)
Note that you have to use a double-quoted string, so \n
is actually interpreted as a line-break.
(See that manual page for more details.)
这篇关于如何将字符串放入数组中,并用新行分隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文