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';
}

$Patternisの場合"/^\d{2}/"、trueが返され、数値「12」と一致します。


私の間違い。上記のコードはうまく機能します。

実際のコードでは、$ Stringは変数から割り当てられ、常に私が気付いていなかったドットで終わります。

上記の下2桁に一致するための要件は、問題の説明のためだけです。式は実際のコードで必要です。

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 に答える