4

我有下面的if语句,它永远不会返回 True。怎么了?

我是 PHP 和正则表达式的新手。

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

// I intend to match '56', which are the last two digits of the string.

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

如果$Pattern"/^\d{2}/",则返回 true 并匹配数字 '12';


我的错。上面的代码运行良好。

在实际代码中,$String 是从一个变量分配的,它总是以一个我不知道的点结束。

匹配上面最后两位数字的要求仅用于问题解释。该表达式在实际代码中是必需的。

4

1 回答 1

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
}
于 2013-03-20T08:24:23.567 回答