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));
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));
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.
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.
Use preg_match
to extract the values into $matches
:
preg_match("/([0-9]+) out of ([0-9]+)/", $text, $matches);
$text = '1 out of 23';
preg_match('/\d+ out of (\d+)/', $text, $matches);
$lastnum1 = $matches[1];
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);
You can use preg_match()
if you can't predict the format of the input string, or sscanf()
if the string format is predictable.
Code: (Demo)
$text = "1 out of 23";
echo preg_match('/\d+(?=\D*$)/', $text, $m) ? $m[0] : '';
echo "\n";
echo sscanf($text, '%*d out of %d')[0];
echo "\n--- \n";
$text = "1 out of 23 more";
echo preg_match('/\d+(?=\D*$)/', $text, $m) ? $m[0] : '';
echo "\n";
echo sscanf($text, '%*d out of %d')[0];
All both techniques on both input strings return 23
.
In regex, \d
means a digital character and \D
means a non-digital character.
With sscanf()
, %d
captures one or more digital characters and %*d
matches but does not capture one or more digital characters.