php preg替换容器内的字符

时间:2011-11-06 04:52:45

标签: php regex preg-replace

是否存在preg_replace()的正则表达式,如果它在单/双引号和圆形/方形/花括号之间,将替换字符串中的字符。

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", 

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

干杯。

1 个答案:

答案 0 :(得分:0)

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

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

这会在REPLACEME(["后跟'后搜索)的任何实例, ]"'之间没有结束字符()]"')。

匹配括号的集合不是常规语言,因此不能用正则表达式表示。所以像((replace, )here,)这样的字符串变得模棱两可,第二个逗号不会被替换。

编辑:我意识到我忘了逃避单引号。修复(晚了几年,但总比没有好)