PHP正则表达式添加rel=“”;nofollow”;到外部链接


PHP regular expression to add rel="nofollow" to external links

我需要将rel="nofollow"添加到所有外部链接(不指向我的网站或其子域)。

我分两步完成,首先我使用以下正则表达式将rel="nofollow"添加到所有链接(甚至内部链接):

<a href="http([s]?)://(.*?)"

然后在第二步中,我使用以下正则表达式消除内部链接(我的网站及其子域)的rel="nofollow"

<a href="http([s]?)://(www'.|forum'.|blog'.)mysite.com(.*?)" rel="nofollow"

我怎么能一步到位?有可能吗?

DOM方式:

$doc = new DOMDocument();
@$doc -> loadHTMLFile($url); // url of the html file
$links = $doc->getElementsByTagName('a');
foreach($links as $link) {
    $href = $link->getAttribute('href');
    if (preg_match('~^https?://(?>[^/m]++|m++(?!ysite.com'b))*~', $href))
        $link->setAttribute('rel', 'nofollow');
}
$doc->saveHTMLFile($url);