使用preg_match_all将<;a href非mailto:链接


Use preg_match_all to pull all <a href links that are NOT mailto: links

我正在尝试使用preg_match_all扫描页面的源,并将所有mailto:链接拉入一个数组,将所有不是mailto:的链接拉入另一个数组。目前我正在使用:

$searches = array('reg'=>'/href(=|=''|='")(?!mailto)(.+)'"/i','mailto'=>'/href(=|=''|='")(?=mailto)(.+)'"/i');
foreach ($searches as $key=>$search)
{
    preg_match_all($search,$source,$found[$key]);
}

mailto:links搜索运行良好,但我找不到非mailto:link搜索同时拉取mailto:和非mailto:链接的原因,即使有否定的前瞻性断言。我做错了什么?

一个不那么脆弱的更明智的解决方案是使用DOMDocument。。。

$dom = new DOMDocument;
$dom->loadHTML($html);
$mailLinks = $nonMailLinks = array();
$a = $dom->getElementsByTagName('a');
foreach($a as $anchor) {
   if ($anchor->hasAttribute('href')) {
      $href = trim($anchor->getAttribute('href'));
      if (substr($href, 0, 7) == 'mailto:') {
            $mailLinks[] = $href;
      } else {
            $nonMailLinks[] = $href;
      }
   }
}

CodePad。

您的正则表达式在此处查找最短的替代方案:

 (=|=''|='")

您要么需要最后对=进行排序,要么使用更常见的:

 =['''"]?

可替换地/或以其它方式将CCD_ 3交换为更明确/限制性的CCD_。因此,与.+ 匹配的""mailto:"否定断言不会失败