2011-11-06 86 views
0

是否存在preg_replace()的正则表达式,它将替换字符串中的字符(如果它位于单/双引号和圆/方括号/大括号之间)。php preg替换容器内的字符

E.g.

$var = "(replace, here) not,here 'but, here' , [and, this too] , \"oh, escaped as well\", "; 
echo preg_replace($pattern, ".", $var); 

将返回:

(replace. here) not,here 'but. here' , [and. this too] , "oh. escaped as well", 

我吸的正则表达式。所以任何帮助将不胜感激。

干杯。

回答

0

只要匹配的括号不重要,就可以完成。

$var = "(replace, here) not,here 'but, here' , [and, this too] , \"oh, escaped as well\", "; 
preg_replace('/[(["'][^)\]"\'].*(REPLACEME).*[)\]"\']/', 'REPLACEWITH', $var); 

此搜索的REPLACEME任何实例后([",或'和后跟一个)]",或'在没有结束字符()]"')之间。

但是,匹配括号的集合并非常规语言,因此无法用正则表达式表示。所以像((replace,)here,)这样的字符串变得模糊不清,第二个逗号将不会被替换。

编辑:我意识到我忘了逃避我的单引号。 Fix'd(迟了几年,但比从未好)