Reputation: 2943
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.
Upvotes: 0
Views: 74
Reputation: 626748
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.Upvotes: 5