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.
remove brackets
Moderator: General Moderators
- prometheuzz
- Forum Regular
- Posts: 779
- Joined: Fri Apr 04, 2008 5:51 am
Re: remove brackets
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
Oh, man, thank you!
You don't have to, but would you please explain this regex.
You don't have to, but would you please explain this regex.
- prometheuzz
- Forum Regular
- Posts: 779
- Joined: Fri Apr 04, 2008 5:51 am
Re: remove brackets
You're welcome.eyespark wrote:Oh, man, thank you!
Not a problem. Here goes:eyespark wrote:You don't have to, but would you please explain this regex.
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 parenthesisMatch 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
Great! Thanks again!
- prometheuzz
- Forum Regular
- Posts: 779
- Joined: Fri Apr 04, 2008 5:51 am
Re: remove brackets
No problem.eyespark wrote:Great! Thanks again!