Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php preg_match to match chars at end of the string

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.

like image 702
user1553857 Avatar asked Jan 14 '23 21:01

user1553857


1 Answers

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
}
like image 162
juco Avatar answered Jan 19 '23 11:01

juco