Php 添加rel=";nofollow";到Wordpress帖子中的所有链接
我想在我的wordpress帖子中的所有链接中添加一个rel=“nofollow”,并且我希望能够有一个无法获得nofollow的链接列表 我已经尝试了很多,但我不能把它做好,因为我真的不能很好地理解正则表达式Php 添加rel=";nofollow";到Wordpress帖子中的所有链接,php,wordpress,Php,Wordpress,我想在我的wordpress帖子中的所有链接中添加一个rel=“nofollow”,并且我希望能够有一个无法获得nofollow的链接列表 我已经尝试了很多,但我不能把它做好,因为我真的不能很好地理解正则表达式 因此,我有字符串$text,我想将a href=“url”>替换为a href=“url”rel=“nofollow”>除非href与某些特定域匹配。假设您添加了一个类到不希望被跟踪的链接 $skipClass = 'preserve-rel'; $dom = new DOMDocum
因此,我有字符串$text,我想将a href=“url”>替换为a href=“url”rel=“nofollow”>除非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
,除了上面定义了类的链接。更新了选项概述