Search code examples
phpregexpreg-matchpreg-match-all

Preg match returning empty array


I did the preg match below to get the hrefs that contain channels OR lifestyle-channels OR esports-channels but it is returning in addition to the correct array an empty array. I imagine there's something wrong with my expression

$re = '/(?!<a href=")(?=(\/(?|channels|lifestyle-channels|esports-channels)\/[a-z 0-9-\_]{1,}))/m';

$str = '<div class="thumb-block "><div class="thumb-inside"><div class="thumb"><a href="/video55783515222/12/best_ronaldinho_plays"><img src="lightbox-blank.gif" data-src="12.jpg" data-idcdn="10" /></a></div><span class="video-hd-mark">1080p</span></div><div class="thumb-under"><p class="title"><a href="/video55783515/13/big_tips_12" title="Tips #12">Tips #12</a></p><p class="metadata"><span class="bg"><span class="duration">26 min</span><a href="/channels/tips_12"><span class="name">Tips #12</span></a><span class="text-disabled"> 20 mins ago</span></span></p></div></div>';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result

var_dump($matches);

result

array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(0) ""
    [1]=>
    string(17) "/channels/tips_12"
  }
}

what i would like

array(1) {
  [0]=>
  array(1) {
    [0]=>
    string(17) "/channels/tips_12"
  }
}

Solution

  • Try (?<!<a[ ]href=")/(?|channels|lifestyle-channels|esports-channels)/[a-z 0-9\-\_]+

    Some notes

    • Can not have assertions that conflict. (?!B)(?=A) will always match A
    • Remove assertion (?=()) and capture group. this will result in the match var group 0 having a value.