我想explode
为所有人提供一个字符串:
但这不起作用:
$keywords = explode("\n\t\r\a,-", "my string");
怎么做?
答案 0 :(得分:57)
爆炸不能那样做。有一个很好的函数叫preg_split
。这样做:
$keywords = preg_split("/[\s,-]+/", "This-sign, is why we can't have nice things");
var_dump($keywords);
输出:
array
0 => string 'This' (length=4)
1 => string 'sign' (length=4)
2 => string 'is' (length=2)
3 => string 'why' (length=3)
4 => string 'we' (length=2)
5 => string 'can't' (length=5)
6 => string 'have' (length=4)
7 => string 'nice' (length=4)
8 => string 'things' (length=6)
顺便说一句,不要使用split
,不推荐使用。
答案 1 :(得分:6)
...或者如果你不喜欢正则表达式并且你仍想要爆炸,你可以在爆炸之前只用一个字符替换多个字符:
$keywords = explode("-", str_replace(array("\n", "\t", "\r", "\a", ",", "-"), "-",
"my string\nIt contains text.\rAnd several\ntypes of new-lines.\tAnd tabs."));
var_dump($keywords);
这吹进了:
array(6) {
[0]=>
string(9) "my string"
[1]=>
string(17) "It contains text."
[2]=>
string(11) "And several"
[3]=>
string(12) "types of new"
[4]=>
string(6) "lines."
[5]=>
string(9) "And tabs."
}