PHP's preg_match() to match characters at the end of a string

php, preg-match, regex

Solution

You are correct.

$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
}

Problem

I have the below if statement, and it never returns True. What is wrong? I am new to PHP and regular expressions. ``` $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'; } ``` If the `$Pattern` is `"/^\d{2}/"`, true is returned and matched the number '12'; My mistake. The above code works well. In the actual code, the $String is assigned from a variable and it always end up with a dot which I was unaware of. The requirement to match the last two digits above is just for issue explanation. The expression is required in actual code.

Original source