Search code examples
phpregexstringintegertext-extraction

Get last whole number in a string


I need to isolate the latest occurring integer in a string containing multiple integers.

How can I get 23 instead of 1 for $lastnum1?

$text = "1 out of 23";
$lastnum1 = $this->getEval(eregi_replace("[^* out of]", '', $text));

Solution

  • you could do:

    $text = "1 out of 23";
    if(preg_match_all('/\d+/', $text, $numbers))
        $lastnum = end($numbers[0]);
    

    Note that $numbers[0] contains array of strings that matched full pattern,
    and $numbers[1] contains array of strings enclosed by tags.