14

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));
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
yan
  • 480
  • 1
  • 11
  • 21
  • 1
    FYI, according to the [PHP Manual](http://php.net/manual/en/function.eregi-replace.php), `eregi_replace` is deprecated and shouldn't be used. Should probably use [`preg_replace`](http://php.net/manual/en/function.preg-replace.php) instead. – Travesty3 Sep 25 '12 at 19:09

7 Answers7

32

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.

Top-Master
  • 7,611
  • 5
  • 39
  • 71
DiverseAndRemote.com
  • 19,314
  • 10
  • 61
  • 70
  • I used your code and it works. Thanks. Can you explain how the code works? – yan Sep 25 '12 at 19:25
  • 4
    The code works by matching all of the grouped integers in your string and puts them into an array. The last element of the array is then used as your answer. – DiverseAndRemote.com Sep 25 '12 at 20:04
4
$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);
} 
Glavić
  • 42,781
  • 13
  • 77
  • 107
faq
  • 2,965
  • 5
  • 27
  • 35
4

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.

Toto
  • 89,455
  • 62
  • 89
  • 125
1

Use preg_match to extract the values into $matches:

preg_match("/([0-9]+) out of ([0-9]+)/", $text, $matches);
Tchoupi
  • 14,560
  • 5
  • 37
  • 71
1
$text = '1 out of 23';
preg_match('/\d+ out of (\d+)/', $text, $matches);
$lastnum1 = $matches[1];
mcrumley
  • 5,682
  • 3
  • 25
  • 33
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);
JavierIEH
  • 743
  • 8
  • 19
1

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.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136