如何以编程方式将 rel= "external" 添加到 HTML 字符串中的外部链接?



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

如果它们是,我如何将external值附加到它们的rel属性?如果它们没有此属性,则附加rel="external" ?

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

$html = preg_replace_callback("#<as[^>]*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">';
    }
}

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

使用XML解析器,如SimpleXML。Regex不是用来做XML/HTML解析的,下面是对解析过程的完美解释:Regex匹配除了XHTML自包含标记之外的打开标记。

将输入解析为XML,使用解析器选择所需的元素,使用解析器编辑它们的属性,然后输出。

它将省去你的头痛,因为正则表达式让我哭泣…


我是这样做的(没有测试):

<?php
$xmlString = "This is where the HTML of your site should go. Make sure it's valid!";
$xml = new SimpleXMLElement($xmlString);
foreach($xml->getElementsByTagName('a') as $a)
{
  $attributes = $a->attributes();
  if (isThisExternal($attributes['href']))
  {
    $a['rel'] = 'external';
  }
}
echo $xml->asXml();
?>

在客户端这样做可能更容易,使用jQuery:

<script type="text/javascript">
    $(document).ready(function()
    {
        $.each($('a'), function(idx, tag)
        {
            // you might make this smarter and throw out URLS like 
            // http://www.otherdomain.com/yourdomain.com
            if ($(tag).attr('href').indexOf('yourdomain.com') < 0)
            {
                $(tag).attr('rel', 'external');
            }
        });
    });
</script>

正如Craig White指出的那样,这并没有做任何seo方面的事情,也不会帮助那些禁用JavaScript的用户。

最新更新