Question

I'm trying to get my head around regex, and I'm failing miserably.

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

For example:

This string (is an example).

Would become:

This string (isanexample).
Was it helpful?

Solution

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

OTHER TIPS

You need to do this recursively. One regex won't do it.

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

What this does is the first pattern finds all of the text within the parens. It passes this match on to the named method (or in this case an anonymous method). The return of the method is used to replace what was matched.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top