Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Preg_替换括号之间的空格_Php_Regex_Preg Replace - Fatal编程技术网

Php Preg_替换括号之间的空格

Php Preg_替换括号之间的空格,php,regex,preg-replace,Php,Regex,Preg Replace,我正试着在regex周围转一转,但我失败得很惨 我有一个字符串,我想匹配并删除两个括号之间的所有空格 例如: This string (is an example). 将成为: This string (isanexample). 您需要递归地执行此操作。一个正则表达式不行 $line = preg_replace_callback( '/\(.*\)/', create_function( "\$matches",

我正试着在regex周围转一转,但我失败得很惨

我有一个字符串,我想匹配并删除两个括号之间的所有空格

例如:

This string (is an example).
将成为:

This string (isanexample).

您需要递归地执行此操作。一个正则表达式不行

$line = preg_replace_callback(
        '/\(.*\)/',
        create_function(
            "\$matches",
            "return preg_replace('/\s+/g','',\$matches);"
        ),
        $line
    );
这样做的第一个模式是查找paren中的所有文本。它将此匹配传递给命名方法(或者在本例中是匿名方法)。方法的返回用于替换匹配的内容。

您可以使用


杰出的我现在遇到了一个新问题,但是您的演示很有效:)要详细说明,如果我想在每行多行上运行它(在每行上查找括号,并删除每行括号之间的空格),该怎么办?它也适用于多行。您可以添加到regexp
m
修饰符,但不需要。测试:
“此字符串(是一个示例)。\n\t\t\t(foo-bar-baz)…”
$str = "This string (is an example).";
$str = preg_replace_callback("~\(([^\)]*)\)~", function($s) {
    return str_replace(" ", "", "($s[1])");
}, $str);
echo $str; // This string (isanexample).