正则表达式代码preg_split(:)

时间:2016-10-17 16:54:32

标签: php arrays regex string

以下代码:

$string = "hello: Mister, Winterbottom";

$words = preg_split("/[\s,]+/", $string);
print_r ($words);

我明白了:

Array ( [0] => hello: [1] => Mister [2] => Winterbottom )

但我希望结果是:

Array ( [0] => hello [1] => Mister [2] => Winterbottom )

这样它就会忽略冒号。我该怎么办?

2 个答案:

答案 0 :(得分:1)

如果您需要使用:扩展角色类,只需将其放入其中并使用

即可
/[\s,:]+/

its demo here。或者,只需使用/\W+/分割1个非单词字符。

$words = preg_split("/[\s,:]+/", $string);
print_r ($words);
// Or
print_r(preg_split("/\W+/", $string));

请参阅PHP demo

答案 1 :(得分:0)

$string = "hello: Mister, Winterbottom";

$words = preg_split("/[\s,]+/", $string);

$words[0] = rtrim($words[0],":");

print_r ($words);