2011-05-10 50 views
2

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

我一直在尝试很多,但我无法完成它,因为我真的无法很好地理解正则表达式。

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

回答

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到各个环节,除了那些上面定义的类。

相关问题