match specific word between brackets

2019-09-17 09:22发布

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.

2条回答
别忘想泡老子
2楼-- · 2019-09-17 09:32

You can use this regex:

\(.*?SpecificWord.*?\)

and replace it with:

any other string
查看更多
欢心
3楼-- · 2019-09-17 09:51

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
查看更多
登录 后发表回答