繁体   English   中英

将rel =“ nofollow”添加到Wordpress帖子中的所有链接

[英]Adding rel=“nofollow” to all links in Wordpress posts

我想在我的wordpress帖子中的所有链接中添加rel =“ nofollow”,并且希望能够获得不会得到nofollow的链接列表。

我已经做了很多尝试,但是我做得不好,因为我真的不太了解regex。

因此,我有字符串$ text,我想用href =“ url” rel =“ nofollow”>替换href =“ url”>,除非href匹配某些特定域。

假设您向不想添加的链接添加了一个类...

$skipClass = 'preserve-rel';

$dom = new DOMDocument;

$dom->loadHTML($str);

$anchors = $dom->getElementsByTagName('a');

foreach($anchors as $anchor) { 
    $rel = array(); 

    if ($anchor->hasAttribute('class') AND preg_match('/\b' . preg_quote($skipClass, '/') . '\b/', $anchor->getAttribute('class')) {
       continue;
    }

    if ($anchor->hasAttribute('rel') AND ($relAtt = $anchor->getAttribute('rel')) !== '') {
       $rel = preg_split('/\s+/', trim($relAtt));
    }

    if (in_array('nofollow', $rel)) {
      continue;
    }

    $rel[] = 'nofollow';
    $anchor->setAttribute('rel', implode(' ', $rel));
}

var_dump($dom->saveHTML());

这会将nofollow添加到除具有上述类的链接之外的所有链接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM