我想在我的wordpress帖子中的所有链接中添加一个rel="nofollow",我希望能够有一个不会得到nofollow的链接列表。
我一直在尝试很多,但我无法正确完成它,因为我真的不能很好地理解正则表达式。
所以我有字符串$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
。