質問

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