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

时间:2011-05-10 09:53:30

标签: php wordpress

我想在我的wordpress帖子中为所有链接添加一个rel =“nofollow”,我希望能够获得一个无法获得nofollow的链接列表。

我一直在努力,但我无法正确完成,因为我真的无法理解正则表达式。

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

1 个答案:

答案 0 :(得分:4)

假设您为不希望被关注的链接添加了一个类...

$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添加到除上面定义的类之外的所有链接。

相关问题