2

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.

qJake
  • 16,821
  • 17
  • 83
  • 135
Dennis
  • 704
  • 1
  • 9
  • 25

2 Answers2

0

You can use this regex:

\(.*?SpecificWord.*?\)

and replace it with:

any other string
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • it replace only the specific word, and I need to replace all the content inside the brackets where specific word exists include brackets. xxx(yyySPECIFWORDyy)xxx => xxxREPLACExxx. I tried '~(.*?)(\(.*SPECIFICWORD.*\))(.*?)~' but it replace all the content from the first brackets in the text. tnx 4 try – Dennis Apr 28 '14 at 14:14
  • 1
    It should be stated that `.*` is ''greedy'', meaning it will take as many characters as it can, including any brackets. So that's why it started at the first bracket in your first attempt, instead of the first one before your word as you intended. The question mark makes it instead match as few characters as possible. You could also write `\([^(]*SpecificWord[^)]*\)` to achieve the same. – SvenS Apr 28 '14 at 14:28
0

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
zx81
  • 41,100
  • 9
  • 89
  • 105
  • Unfortunately this does not cover the case where the SPECIFICWORD is right next to the brackets. Example: – Peurke Sep 06 '22 at 11:33