/**
* Remove all parentheses and the text inside them.
*
* @param string $text The input string
* @return string The cleaned string
*/
function removeParenthesesWithContent(string $text): string {
// Regex explanation:
// \( → match opening parenthesis
// [^)]* → match any characters until a closing parenthesis
// \) → match closing parenthesis
// The 'g' behavior is automatic in PHP's preg_replace (replaces all)
$cleaned = preg_replace('/\([^)]*\)/', '', $text);
// Trim extra spaces created after removal
return trim(preg_replace('/\s+/', ' ', $cleaned));
}
$str = "(An) API (API) (is a) (connection) connects (between) computer programs";
$output = removeParenthesesWithContent($str);
echo $output;
/*
run:
API connects computer programs