AlexV
AlexV

Reputation: 23118

How to clear text between parentheses with a regular expression in PHP?

The question Remove Text Between Parentheses PHP works but only with "full" parentheses (opening and closing):

preg_replace('/\([^)]+\)/', '', $myString);

But I need it to work with unclosed parentheses too. For example:

$string1 = 'Something (unimportant stuff'; //Becomes 'Something '
$string2 = '(unimportant stuff'; //Becomes '' (empty string)
$string3 = 'Something (bad) happens'; //Becomes 'Something  happens'
$string4 = 'Something)'; //Stays the same

I don't really care if I must do it with two passes (using the original answer and a new one)...

Upvotes: 2

Views: 249

Answers (3)

bukart
bukart

Reputation: 4906

try it with this regex /^[^(]*\)|\([^)]*$|\([^()]*\)/

this will match phrases with no opening but closing brace, with opening but no closing brace and also with opening and closing braces

Upvotes: 0

melwil
melwil

Reputation: 2553

What about it doesn't already work? If it's only the unclosed ones, you can search for a closing parenthesis or end of line?

preg_replace('/\([^)]+(\)|$)/', '', $myString);

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173662

You could make the final closing parentheses optional:

preg_replace('/\([^)]+\)?/', '', $myString);
                        ^

Upvotes: 4

Related Questions