Matthew Collins
Matthew Collins

Reputation: 109

Preg_replace spaces between brackets

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

Upvotes: 3

Views: 1335

Answers (2)

Kerem
Kerem

Reputation: 11586

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

Upvotes: 4

Erik Nedwidek
Erik Nedwidek

Reputation: 6184

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.

Upvotes: 0

Related Questions