Joshc
Joshc

Reputation: 3853

PHP how to extract 3 digits from a string and output it

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...

  1. TZR9000 Supertroop 2014 001
  2. FZR Mode 900 Impact 2014 003 Accessories
  3. NICE750 Destroyer 2014 020

But then it fails on this string...

  1. We like the moon 2013 Stand 010

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

Answers (3)

bukart
bukart

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:

Regular expression visualization

Upvotes: 1

Nir Alfasi
Nir Alfasi

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

jeroen
jeroen

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

Related Questions