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
  • 21,673
  • 11
  • 52
  • 88
Googlebot
  • 13,096
  • 38
  • 113
  • 210

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
  • 83,228
  • 5
  • 85
  • 113
mrzasa
  • 21,673
  • 11
  • 52
  • 88