[英]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.