Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I grab last number in a string in PHP?

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));
like image 444
yan Avatar asked Sep 25 '12 19:09

yan


People also ask

How can I get the last part of a string in PHP?

strrchr returns the portion of the string after and including the given char, not a numeric index. So you would want to do $last_section = substr(strrchr($string, '. '), 1); to get everything after the char.

How do I cut a string after a specific character in PHP?

The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.

How do I get the first digit of a number in PHP?

echo substr($mynumber, 0, 2);


5 Answers

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.

like image 114
DiverseAndRemote.com Avatar answered Oct 22 '22 09:10

DiverseAndRemote.com


$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);
} 
like image 26
faq Avatar answered Oct 22 '22 10:10

faq


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.

like image 2
Toto Avatar answered Oct 22 '22 08:10

Toto


Use preg_match to extract the values into $matches:

preg_match("/([0-9]+) out of ([0-9]+)/", $text, $matches);
like image 1
Tchoupi Avatar answered Oct 22 '22 08:10

Tchoupi


$text = '1 out of 23';
preg_match('/\d+ out of (\d+)/', $text, $matches);
$lastnum1 = $matches[1];
like image 1
mcrumley Avatar answered Oct 22 '22 08:10

mcrumley