Here is a very simple piece of code:
<?php
$matches = array();
$str = "You came in 21st out of 53";
preg_match("/(\d+).*(\d+)/",$str,$matches);
echo var_dump($matches);
?>
I am learning and experimenting with PHP's preg_match and regular expressions. I thought the code above would capture "21" and "53", but what it actually captures is "21" and "3".
Here is the result of echo var_dump($matches);
array(3) {
[0]=> string(14) "21st out of 53"
[1]=> string(2) "21"
[2]=> string(1) "3"
}
How do I write the regular expression to capture "53"? I hope the answer can be general enough that it could also capture "153" and "jkj53hjjk" (so that the expression is not changed to "/(\d+).*(\b\d+)/" .
If discussion is possible, why is it that when capturing the first number, it does so greedily, but when capturing the second number, it is not greedy? Is it capturing the number backwards and is therefore happy to stop at the first digit it finds? Can this be overcome?
This is my first post to Stack Overflow. I researched this question quite a bit, but I could not find an answer.