2009-11-08 65 views
1

我想分割字母数字(带空格)和非字母数字用逗号分隔一个字符串。PHP正则表达式替换?

我这个尝试...

$str = "This is [email protected]#$%^&"; 
preg_replace("/([a-z0-9_\s])([^a-z0-9_])/i", "$1, $2", $str); 

但我得到这个结果...

这就是!@#$%^ &

如何我可以修复搜索pattarn以获得此结果吗?

这就是!@#$%^ &

感谢。

回答

3

你应该已经否定了第一组中的一切第二,像这样:

preg_replace("/([a-z0-9_\s])([^a-z0-9_\s])/i", "$1, $2", $str); 

否则,它会在空间划分为好。

+0

这将工作为他的榜样文本,但,因为分裂的正则表达式是静态的,它可能会不为别的 – 2009-11-08 05:14:49

+0

很抱歉,但你是什么意思的工作?可以分享一些它会失败的例子吗? – 2009-11-11 06:38:39

0

您可能必须在多次迭代中执行此操作。试试这个:

$preg = array("/([\w\s]+)/i", "/([\W\s]+)/i"): 
$replace = array("\\1, ", "\\1 "); 
$result = rtrim(preg_replace($preg, $replace, $input)); // rtrim to get rid of any excess spaces