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).
有帮助吗?

解决方案

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top