phpregexstringsanitizationparentheses

Remove all parenthetical expressions from a string and remove lingering spaces


$item = "(1) Robin Hood (hero)";

Text inside brackets can be changed.

How do I remove all the brackets with text inside them from the string?

We should get this:

$item = "Robin Hood";

Solution

  • You can use preg_replace as:

    $item = preg_replace('/\(.*?\)/s','',$item);
    

    Looks like you also want to remove leading and trailing spaces after the replacement.
    You can make use of trim for that as:

    $item = trim( preg_replace('/\(.*?\)/s','',$item));
    

    The regex used is \(.*?\):