Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/11.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 包裹预处理单独替换重复组_Php_Regex - Fatal编程技术网

Php 包裹预处理单独替换重复组

Php 包裹预处理单独替换重复组,php,regex,Php,Regex,我有一个简单的PHP正则表达式,我用它来替换字符串 $pat='/\$(\w+)/'; $repl='f("${1}")'; echo preg_replace($pat,$repl,'This is a $test.'); 例如,这可以翻译为: This is a $test. 进入: 但现在我想稍微改变一下,这样我就可以匹配多个逗号分隔的单词,并单独包装它们,如下所示: This is a $test,red,green,blue. 应成为: This is a f("test","r

我有一个简单的PHP正则表达式,我用它来替换字符串

$pat='/\$(\w+)/';
$repl='f("${1}")';
echo preg_replace($pat,$repl,'This is a $test.');
例如,这可以翻译为:

This is a $test.
进入:

但现在我想稍微改变一下,这样我就可以匹配多个逗号分隔的单词,并单独包装它们,如下所示:

This is a $test,red,green,blue.
应成为:

This is a f("test","red","green","blue")
我可以很容易地想出这个模式:

$pat='/\$([\w,]+)/';
但我不知道如何单独包装重复组的每个元素。使用现有替代品,我得到:

This is a f("test,red,green,blue")
尝试类似于:

$repl='f(${"1"})';

破坏引用,显然不起作用。

要做到这一点,您必须使用回调函数,然后稍微修改替换项,首先将逗号分隔的匹配项放入数组中,然后将其返回到字符串中,您可以在其中加引号,例如

替换:

$repl = function($m){
    return 'f("' . implode("\",\"", explode(",", $m[1])) . '")';
};
函数调用:

preg_replace($pat, $repl, $str); → preg_replace_callback($pat, $repl, $str); 预更换($pat,$repl,$str);→ 预替换回调($pat、$repl、$str);
我想在这个函数中有一个遗漏或额外的引用?@Michael是的,当我从我的编辑器中复制它时,真的有点搞砸了。现在更换应该是正确的。 preg_replace($pat, $repl, $str); → preg_replace_callback($pat, $repl, $str);