Preg_replace spaces between brackets

I am trying to get my head up around regex and I am failing.

I have a string and I want to match and remove every space between two brackets.

For example:

This string (is an example).

      

It would become:

This string (isanexample).

      

+3


source to share


2 answers


You can use preg_replace_callback ;



$str = "This string (is an example).";
$str = preg_replace_callback("~\(([^\)]*)\)~", function($s) {
    return str_replace(" ", "", "($s[1])");
}, $str);
echo $str; // This string (isanexample).

      

+3


source


You need to do it recursively. Regular expression alone won't do this.

$line = preg_replace_callback(
        '/\(.*\)/',
        create_function(
            "\$matches",
            "return preg_replace('/\s+/g','',\$matches);"
        ),
        $line
    );

      



What it is, the first template finds all the text inside parens. It passes this correspondence to the specified method (or in this case to the anonymous method). The method return is used to replace what matched.

0


source







All Articles