user1568231
user1568231

Reputation: 3

How to use preg_match_all to get different variables out of a string

I want to know how to get the identifier the number1 and the number2 out of this string.

NAME  IDENTIFIER-NUMBER1-NUMBER2

example:

John Doe ABC-3901-11801

I want to get the IDENTIFIER NUMBER1 and NUMBER2 seperatly into different variables.

But the problem is that i dont always know on what position it is or if there is extra text behind it like so:

Blablabla ABC-3901-11801 John Doe Blablabla

ofc there can also be different numbers and letters:

XYZ-46781-28102

Can anybody please explain me how to find those variables in php.

Thanks in advance

Upvotes: 0

Views: 173

Answers (1)

Tivie
Tivie

Reputation: 18923

Under the assumption that:

  • Identifier is always uppercase
  • Identifier is always composed of 3 letters
  • Number1 only has numbers and is always preceded by dash
  • Number2 only has numbers and is always preceded by dash

This regex will work -> '/([A-Z]{3})-([0-9]*)-([0-9]*)/'

example:

$data = 'Blablabla ABC-3901-11801 John Doe Blablabla';
preg_match_all('/([A-Z]{3})-([0-9]*)-([0-9]*)/', $data, $matches, PREG_PATTERN_ORDER);
var_dump($matches);

this will output

array
  0 => 
    array
      0 => string 'ABC-3901-11801' (length=14)
  1 => 
    array
      0 => string 'ABC' (length=3)
  2 => 
    array
      0 => string '3901' (length=4)
  3 => 
    array
      0 => string '11801' (length=5)
  • $matches[1] is always the identifier
  • $matches[2] is always number1
  • $matches[3] is always number2

EDIT: Here's also a more generic regex:

/([A-Za-z]*)-([0-9]*)-([0-9]*)/

This only assumes that the IDENTIFIER only contains letter (in any number and in uppercase or lowercase)

this regex, for instance, works in this case

Blablabla abcdef-3901-11801 John Doe Blablabla

Upvotes: 1

Related Questions