简体   繁体   English

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

[英]PHP Regex - What is the difference between $1 and \1?

The two following codes give the same result: 以下两个代码给出了相同的结果:

$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

But two the following codes give different result: 但是以下两个代码给出了不同的结果:

$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

Does this mean \\1 and $1 is different? 这是否意味着\\ 1和$ 1不同?

Neither of those does what you want. 这些都不符合你的要求。 In your code, the md5 function is called on the literal string '\\1' or "$1" (the difference between backslash and dollar sign being the difference in the checkums), and then preg_replace is passed the result of that md5 call, which never had a chance to consider the string it's trying to match. 在你的代码中, md5函数在文字字符串'\\1'"$1"上调用(反斜杠和美元符号之间的差异是校验和中的差异),然后preg_replace传递md5调用的结果 ,从来没有机会考虑它试图匹配的字符串。

What you want in this case is to use preg_replace_callback : 在这种情况下你想要的是使用preg_replace_callback

echo preg_replace_callback('/a (test)/', function($m) { return md5($m[1]); }, $test);

The argument passed to the callback function is an array containing the captured subexpressions, so the equivalent of \\1 or $1 is $m[1] ; 传递给回调函数的参数是一个包含捕获的子表达式的数组,因此等价于\\1$1$m[1] ; \\2 or $2 would be $m[2] , etc. \\2$2将是$m[2]等。

Well that's because you aren't passing \\1 or $1 to the preg_replace call any more, are you?? 好吧那是因为你没有再将\\1$1传递给preg_replace调用,是吗?

\\1 and $1 are synonymous in regex replacement strings. \\1$1是正则表达式替换字符串中的同义词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM