'How do I grab last number in a string in PHP?
How can I get 23 instead of 1 for $lastnum1?
$text = "1 out of 23";
$lastnum1 = $this->getEval(eregi_replace("[^* out of]", '', $text));
Solution 1:[1]
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.
Solution 2:[2]
$text = "1 out of 23";
$ex = explode(' ',$text);
$last = end($ex);
and if you whant to be sure that that last is a number
if (is_numeric(end($ex))) {
$last = end($ex);
}
Solution 3:[3]
Another way to do it:
$text = "1 out of 23";
preg_match('/(\d+)\D*$/', $text, $m);
$lastnum = $m[1];
This will match last number from the string even if it is followed by non digit.
Solution 4:[4]
Use preg_match to extract the values into $matches:
preg_match("/([0-9]+) out of ([0-9]+)/", $text, $matches);
Solution 5:[5]
$text = '1 out of 23';
preg_match('/\d+ out of (\d+)/', $text, $matches);
$lastnum1 = $matches[1];
Solution 6:[6]
If the format will be the same, why not explode the string and convert the last one?
<?php
$text = "1 out of 23";
$words = explode(" ",$text);
$lastnum = (int)array_pop($words);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Top-Master |
| Solution 2 | Glavić |
| Solution 3 | Toto |
| Solution 4 | Tchoupi |
| Solution 5 | mcrumley |
| Solution 6 | JavierIEH |
