2013-03-20 71 views
4

我有一個如下的語句,它永遠不會返回True。哪裏不對?PHP preg_match匹配字符串末尾的字符

我是新來的PHP和正則表達式。

$String = '123456'; 
$Pattern = "/\d{2}$/"; 

//i intend to match '56', which is the last two digit of the string. 

if(preg_match($Pattern $String ,$matches)) 
{ 
echo 'Matched'; 
} 

如果$Pattern"/^\d{2}/",則返回true和匹配數 '12';

編輯: 我的錯誤。上面的代碼運行良好。 在實際的代碼中,$ String是從一個變量中分配出來的,它最終以一個點 而我不知道。 要求匹配上面的最後兩位數字只是爲了解釋問題。正則表達式在實際代碼中是需要的。

+1

不知道是什麼問題,你的代碼似乎對我來說很好嗎? http://codepad.viper-7.com/xDhzmN – w00 2013-03-20 08:21:36

+0

你不需要一個正則表達式來獲取字符串的最後兩個字符。請澄清你想做什麼這個問題的最後一句難以理解。 – AD7six 2013-03-20 08:32:57

回答

9

你是對的。

$String = '123456'; 
$Pattern = "/\d{2}$/"; 
$Pattern2 = "/^\d{2}/"; 

if(preg_match($Pattern, $String ,$matches)) 
{ 
    print_r($matches); // 56 
} 

if(preg_match($Pattern2, $String ,$matches)) 
{ 
    print_r($matches); // 12 
} 
+0

謝謝您的確認。我重新檢查,發現是我的錯誤。我會接受你的回答。 – user1553857 2013-03-20 09:28:47

相關問題