本文介绍了如何以编程方式添加rel =" external"到一串HTML的外部链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查字符串变量中的链接是否为外部链接?此字符串是网站内容(如评论,文章等)。

How can I check if links from a string variable are external? This string is the site content (like comments, articles etc).

如果是,我如何追加外部值为 rel 属性?如果他们没有这个属性,请追加 rel =external

And if they are, how do I append a external value to their rel attribute? And if they don't have this attribute, append rel="external" ?

推荐答案

HTML解析器适用于输入过滤,但是对于修改输出,您需要具有简单的正则表达式解决方案的性能。在这种情况下,回调正则表达式会这样做:

A HTML parser is appropriate for input filtering, but for modifying output you'll need the performance of a simpleminded regex solution. In this case a callback regex would do:

$html = preg_replace_callback("#<a\s[^>]*href="(http://[^"]+)"[^>]*>#",
     "cb_ext_url", $html);

function cb_ext_url($match) {
    list ($orig, $url) = $match;
    if (strstr($url, "http://localhost/")) {
        return $orig;
    }
    elseif (strstr($orig, "rel=")) {
        return $orig;
    }
    else {
        return rtrim($orig, ">") . ' rel="external">';
    }
}

您可能需要更细致的检查。但这是一般方法。

You'll probably need more fine-grained checks. But that's the general approach.

这篇关于如何以编程方式添加rel =&quot; external&quot;到一串HTML的外部链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 08:09