如何在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)...

You could make the final closing parentheses optional:

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

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

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