php preg_match to match chars at end of the string
16,976
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
}
Author by
user1553857
Updated on June 27, 2022Comments
-
user1553857 almost 2 years
I have a below if statement, it never return True. What is wrong?
I am new to php and regex.
$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'; }
if the
$Pattern
is"/^\d{2}/"
, true is returned and matched the number '12';Edit: My mistake. The above code work well. In actual code, the $String is assigned from a variable and it alwasys end up with a dot which i unawared of. The requirement to match the last two digits above is just for issue explanation. Regex is require in actual code.