2011-11-06 82 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(遲了幾年,但比從未好)