0

I would like to know how to capture ALL instances of particular substring within a string. My substring may have 3 variations:

  • AA-123BB
  • AA 123BB
  • AA123BB

The regex I constructed so far is capturing only one instance. I tried many combinations but still no success. Here is my regex: https://regex101.com/r/cXqmcn/2

My PHP code is here:

$x = "klajshf lkjsh allashflkjh BL-345HS sjhg qkjg qwkjh g
qwdewqdwqedwqd BL345HS wqedwqehdljhwqed ZA 456KL
sdcscd";
preg_match('/([A-Z]{2}-?\s?[0-9]{3}[A-Z]{2})+/', $x, $matches);
var_export($matches);

And the result is:

array (
  0 => 'BL-345HS',
  1 => 'BL-345HS',
)

I guess something is wrong while the regex101 site is saying this:

A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data

ANSWER: Aaaah sorry, preg_match_all is all I need in my PHP.

Enriqe
  • 567
  • 1
  • 6
  • 22

0 Answers0