1

I have string like below:

<a href="test1.com">test1</a><a href="test2.com">test2</a>

And my regex is like below:

<a href=(.*?)test2.com(.*?)<\/a>

and my php code:

preg_match('/<a href=(.*?)test2.com(.*?)<\/a>/s',$game,$mat);

So I want to match this whole thing <a href="test2.com">test2</a> , but instead its matching from the beginning of <a href and I get following:

<a href="test1.com">test1</a><a href="test2.com">test2</a>

How do I match from test2.com and match till first left and first right occurances.

mrzasa
  • 22,895
  • 11
  • 56
  • 94
Gracie williams
  • 1,287
  • 2
  • 16
  • 39

1 Answers1

2

Use

<a href=([^<]*)test2.com([^<]*)<\/a>

Demo

Using [^<] instead of .*? assures that repetition will match only text to next html tag (starting with <). Greedy operator with negated class is also faster than lazy operator with dot.

mrzasa
  • 22,895
  • 11
  • 56
  • 94