我想向我的 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
添加到除上面定义的类之外的所有链接。
关于php - 将 rel ="nofollow"添加到 WordPress 帖子中的所有链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5948268/