0

I use preg_match_all to get all matches of a two-part pattern as:

/<(.*?)>[:|\s]+{(.*?)}/

In a string like:

<First>: something <second>: {Second} something <Third>: {Third}

I want to match:

<second>: {Second}

instead of:

<First>: something <second>: {Second}

Working Example

Where did I do wrong?

mrzasa
  • 22,895
  • 11
  • 56
  • 94
Googlebot
  • 15,159
  • 44
  • 133
  • 229

1 Answers1

2

Use limited repeated set instead of lazy repetition inside the brackets:

<([^>]*)>[:\s]+{(.*?)}

The change is to replace <(.*?)> with <([^>]*)>. The initial version matches the first < then takes lazily any character until it finds :{Second}. If you restrict repetition, regex engine will try to start with <First>, but when it doesn't find :{...} after that, it'll try with the next <

Demo

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
mrzasa
  • 22,895
  • 11
  • 56
  • 94