Reputation: 3853
This is a bit a strange issue. I am trying just to get sequential 3 digit integer from a string.
Now I thought I was successfully doing it using this code below...
preg_match_all('!\d+!', $image['title'], $integer); echo $integer[0][2];
But now it seems to be failing on some strings.
It works fine on these strings...
But then it fails on this string...
Is there another possible way to extract the 3 digit integer successfully with out getting confused with other integers. I guess it will have to be a clever bit of php to do this.
The only consistent pattern there is, is there is always a space infront of the 3 digits and either a full-stop or a space after the 3 digits.
Upvotes: 0
Views: 1162
Reputation: 4906
the solidest way should be
preg_match_all('!(\d{3})(?=(?:(?!\d{3}).)*$)!m', $str, $integer);
see it in action here: http://regex101.com/r/pJ0xN4
here's also a structural explanation:
Upvotes: 1
Reputation: 53535
The current regex extracts all the digit-sequences in the title. In order to extract only the last three digits we can use a regex that grabs only the last sequence in the title (space before and "end of the line" = $
) - we'll always have the result in the first item of the result array:
$str = "TZR9000 Supertroop 2014 001";
preg_match_all('! (\d+)$!', $str, $integer);
echo $integer[0][0];
$str = "We like the moon 2013 Stand 010";
preg_match_all('! (\d+)$!', $str, $integer);
echo $integer[0][0];
OUTPUT:
001 010
Upvotes: 0
Reputation: 91734
It depends on the exact requirements, but in the examples you have given, you just need the last element of the array, so you can replace:
echo $integer[0][2];
with:
echo end($integer[0]);
Upvotes: 2