Search code examples
phphtml-parsingpreg-match

PHP preg_match return the string between two strings


How can I get this link "http://example.com/view.php?id=5841" from the code:

<h3 class="coursename"><a class="" href="http://example.com/view.php?id=521">D<span class="highlight">LAW</span> <span class="highlight">130</span>Management</a></h3><div class="moreinfo"></div></div><div class="content"><ul class="teachers"><li>Teacher: <a href="http://example.com/">John</a></li></ul><div class="coursecat">Category: <a class="" href="http://example.com/">First</a></div></div></div><div class="coursebox clearfix even" data-courseid="5841" data-type="1"><div class="info"><h3 class="coursename"><a class="" href="http://example.com/view.php?id=5841"><span class="highlight">LAW</span> <span class="highlight">130`

I tried:

preg_match('/href="(.*)"><span class="highlight">LAW/isU',$BBB,$AAA);

And the result was:

http://example.com/view.php?id=521">D<span class="highlight">LAW</span> <span class="highlight">130</span>Management</a></h3><div class="moreinfo"></div></div><div class="content"><ul class="teachers"><li>Teacher: <a href="http://example.com/">John</a></li></ul><div class="coursecat">Category: <a class="" href="http://example.com/">First</a></div></div></div><div class="coursebox clearfix even" data-courseid="5841" data-type="1"><div class="info"><h3 class="coursename"><a class="" href="http://example.com/view.php?id=5841

Solution

  • Use this instead:

    /href="(.[^<]*?)"><span class="highlight">LAW/isU
    

    It is a simple way of telling Regex to find the shortest expression that matches the one you want.