match specific word between brackets

南楼画角 提交于 2020-01-07 08:33:10

问题


I need match and replace specific word between brackets (including the brackets). something like this:

xxx(xxxxSPECIFICWORDxxxxxxxxxxx)xxx

I need replace this:

(xxxxSPECIFICWORDxxxxxxxxxxx)

my text looks something like this:

xx(xxxx)xxxx(xxxxxxxx)xxx(xxx)xxx(xxxxSPECIFICWORDxxxxxxxxxxx)xxx

I tried write regex with preg_replace the problem that it replace all the text from the first bracket to my last specific word bracket. I realy don't know what to do can someone help me?

thanks.


回答1:


Dennis, use this simple regex:

\([^(]+SPECIFICWORD[^)]+\)

Here is a demo:

<?php
$string = "xx(xxxx)xxxx(xxxxxxxx)xxx(xxx)xxx(xxxxSPECIFICWORDxxxxxxxxxxx)xxx";
$regex="~\([^(]+SPECIFICWORD[^)]+\)~";
echo preg_replace($regex,"\1NEWWORD",$string);
?>

The Output:

xx(xxxx)xxxx(xxxxxxxx)xxx(xxx)xxxNEWWORDxxx



回答2:


You can use this regex:

\(.*?SpecificWord.*?\)

and replace it with:

any other string


来源:https://stackoverflow.com/questions/23342679/match-specific-word-between-brackets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!