0

I am trying to find all the numbers after a capital letter. See the example below:

E1S1 should give me an array containing: [1 , 1]

S123455D1223 should give me an array containing: [123455 , 1223]

i tried the following but didnt get any matches on any of the examples shown above :(

$loc = "E123S5";
$locs = array();
preg_match('/\[A-Z]([0-9])/', $loc, $locs);

any help is greatly appreciated i am a newbie to regex.

Funk Forty Niner
  • 73,764
  • 15
  • 63
  • 131
FutureCake
  • 2,108
  • 16
  • 43
  • Add a [repetition operator](http://www.regular-expressions.info/repeat.html) e.g. `[0-9]+` – revo Jul 23 '17 at 19:54
  • Possible duplicate of [Reference - What does this regex mean?](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – revo Jul 23 '17 at 19:55

1 Answers1

5

Your regex \[A-Z]([0-9]) matches a literal [ (as it is escaped), then A-Z] as a char sequence (since the character class [...] is broken) and then matches and captures a single ASCII digit (with ([0-9])). Also, you are using a preg_match function that only returns 1 match, not all matches.

You might fix it with

preg_match_all('/[A-Z]([0-9]+)/', $loc, $locs);

The $locs\[1\] will contain the values you need.

Alternatively, you may use a [A-Z]\K[0-9]+ regex:

$loc = "E123S5";
$locs = array();
preg_match_all('/[A-Z]\K[0-9]+/', $loc, $locs);
print_r($locs[0]);

Result:

Array
(
    [0] => 123
    [1] => 5
)

See the online PHP demo.

Pattern details

  • [A-Z] - an upper case ASCII letter (to support all Unicode ones, use \p{Lu} and add u modifier)
  • \K - a match reset operator discarding all text matched so far
  • [0-9]+ - any 1 or more (due to the + quanitifier) digits.
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397