How to remove parentheses and the text inside them from a string in PHP

2 Answers

0 votes
/**
 * 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
 

 



answered Aug 13, 2015 by avibootz
edited 4 hours ago by avibootz
0 votes
/**
 * Remove parentheses and their contents without regex.
 */
function removeParenthesesWithContent(string $text): string {
    $result = '';
    $depth = 0;
 
    for ($i = 0; $i < strlen($text); $i++) {
        $char = $text[$i];
 
        if ($char === '(') {
            $depth++;
            continue;
        }
 
        if ($char === ')') {
            if ($depth > 0) $depth--;
            continue;
        }
 
        if ($depth === 0) {
            $result .= $char;
        }
    }
 
    return trim(preg_replace('/\s+/', ' ', $result));
}
 
$input = "(An) API (API) (is a) (connection) connects (between) computer programs";
echo removeParenthesesWithContent($input);
 
 
 
/*
run:
 
API connects computer programs
 
*/

 



answered Aug 13, 2015 by avibootz
edited 4 hours ago by avibootz
...