2013-03-20 219 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