PHP正则表达式-$1和\1之间的区别是什么?

PHP正则表达式-$1和\1之间的区别是什么?,php,regex,Php,Regex,以下两个代码给出相同的结果: $test = "this is a test"; echo preg_replace('/a (test)/','\1',$test); //this is test $test = "this is a test"; echo preg_replace('/a (test)/',"$1",$test); //this is test 但以下两种代码给出了不同的结果: $test = "this is a test"; echo preg_replace('/

以下两个代码给出相同的结果:

$test = "this is a test";
echo preg_replace('/a (test)/','\1',$test); //this is test

$test = "this is a test";
echo preg_replace('/a (test)/',"$1",$test); //this is test
但以下两种代码给出了不同的结果:

$test = "this is a test";
echo preg_replace('/a (test)/',md5('\1'),$test); //this is b5101eb6e685091719013d1a75756a53

$test = "this is a test";
echo preg_replace('/a (test)/',md5("$1"),$test); //this is 06d3730efc83058f497d3d44f2f364e3

这是否意味着\1和$1不同?

这是因为您不再将
\1
$1
传递给
preg\u replace
呼叫,是吗


\1
$1
在正则表达式替换字符串中是同义词。

它们都不是您想要的。在您的代码中,对文本字符串
'\1'
“$1”
(反斜杠和美元符号之间的差异是校验中的差异)调用
md5
函数,然后
preg_replace
传递该
md5
调用的结果,它从来没有机会考虑它想要匹配的字符串。

在这种情况下,您需要使用:

传递给回调函数的参数是一个包含捕获的子表达式的数组,因此
\1
$1
的等价物是
$m[1]
<代码>\2或
$2
将是
$m[2]
,等等。

是否可能重复?
echo preg_replace_callback('/a (test)/', function($m) { return md5($m[1]); }, $test);