2

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)...

Community
  • 1
  • 1
AlexV
  • 22,658
  • 18
  • 85
  • 122

3 Answers3

4

You could make the final closing parentheses optional:

preg_replace('/\([^)]+\)?/', '', $myString);
                        ^
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

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);
melwil
  • 2,547
  • 1
  • 19
  • 34
0

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

bukart
  • 4,906
  • 2
  • 21
  • 40