2011-05-10 89 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到各個環節,除了那些上面定義的類。

相關問題