Page 1 of 1

remove brackets

Posted: Thu Jun 11, 2009 5:03 am
by eyespark
Hi,

I'm lost with this one. Example text:

Lorem ipsum dolor sit (text text text) amet, consectetur adipisicing elit, sed do eiusmod (text keyword1 text keyword2 text) tempor incididunt ut labore et dolore (text keyword3) magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation (text text text) ullamco laboris nisi ut aliquip ex ea commodo consequat.

I need to remove the brackets and its content only if the content contains keyword1 or keyword2 or keyword3.

I managed to remove all brackets, but this condition is killing for a few days now. Please help and thanks in advance.

Re: remove brackets

Posted: Thu Jun 11, 2009 6:12 am
by prometheuzz
This ought to do it:

Code: Select all

$text = 'Lorem ipsum dolor sit (text text text) amet, consectetur adipisicing 
elit, sed do eiusmod (text keyword1 text keyword2 text) tempor incididunt ut 
labore et dolore (text keyword3) magna aliqua. Ut enim ad minim veniam, quis 
nostrud exercitation (text text text) ullamco laboris nisi ut aliquip ex ea 
commodo consequat.';
echo preg_replace('/\((?=[^)]*(?:keyword1|keyword2|keyword3))[^)]*\)/', '', $text);

Re: remove brackets

Posted: Thu Jun 11, 2009 10:22 am
by eyespark
Oh, man, thank you!
You don't have to, but would you please explain this regex.

Re: remove brackets

Posted: Thu Jun 11, 2009 12:18 pm
by prometheuzz
eyespark wrote:Oh, man, thank you!
You're welcome.
eyespark wrote:You don't have to, but would you please explain this regex.
Not a problem. Here goes:

Code: Select all

\(                                 // match an opening parenthesis
(?=                                // start a positive look ahead
  [^)]*                            //   match zero or more characters other than a closing parenthesis
  (?:keyword1|keyword2|keyword3)   //   match 'keyword1', 'keyword2' or 'keyword3'
)                                  // stop the positive look ahead
[^)]*                              // match zero or more characters other than a closing parenthesis
\)                                 // match a closing parenthesis
In plain English this would look like:

Match an opening parenthesis only when there's one of the words 'keyword1', 'keyword2' or 'keyword3' ahead of it, and between the parenthesis and the keyword is not a closing parenthesis. If that first condition is met, then consume zero or more characters other than a closing parenthesis and lastly match a closing parenthesis.

Feel free to ask if there's something unclear to you.

Re: remove brackets

Posted: Fri Jun 12, 2009 4:59 pm
by eyespark
Great! Thanks again!

Re: remove brackets

Posted: Sat Jun 13, 2009 1:52 am
by prometheuzz
eyespark wrote:Great! Thanks again!
No problem.