簡體   English   中英

PHP正則表達式 - $ 1和\\ 1之間有什么區別?

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

以下兩個代碼給出了相同的結果:

$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不同?

這些都不符合你的要求。 在你的代碼中, md5函數在文字字符串'\\1'"$1"上調用(反斜杠和美元符號之間的差異是校驗和中的差異),然后preg_replace傳遞md5調用的結果 ,從來沒有機會考慮它試圖匹配的字符串。

在這種情況下你想要的是使用preg_replace_callback

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

傳遞給回調函數的參數是一個包含捕獲的子表達式的數組,因此等價於\\1$1$m[1] ; \\2$2將是$m[2]等。

好吧那是因為你沒有再將\\1$1傳遞給preg_replace調用,是嗎?

\\1$1是正則表達式替換字符串中的同義詞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM