Скажем, вы добавили класс к ссылкам, на которые вы не хотите переходить ...
$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
ко всем ссылкам, кроме тех, у которых класс определен выше.