문제

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