如何检测并使作者描述中的链接不跟随

时间:2016-09-21 作者:Usman Siddiqui

我的author.php 文件:

 $buffy .= \'<div class="td-author-description">\';
 $buffy .=  get_the_author_meta(\'description\', $author_id);
 $buffy .= \'</div>\';
如何才能$buffy 字符串进行分析,以便作者描述中的链接具有rel="nofollow" 是否自动设置属性?

1 个回复
最合适的回答,由SO网友:Dave Romsey 整理而成

这实际上是一个更一般的PHP问题,但这可以解决问题:

$author_desc = \'<div class="td-author-description">\';
$author_desc .=  get_the_author_meta( \'description\', $author_id );
$author_desc .= \'</div>\';

$dom = new DOMDocument;
$dom->loadHTML( mb_convert_encoding( $author_desc, \'HTML-ENTITIES\', \'UTF-8\' ) );

$sxe = simplexml_import_dom( $dom );

// Process all <a> nodes with an href attribute
foreach ( $sxe->xpath( \'//a[@href]\' ) as $a) {
    if ( empty( $a[\'rel\'] ) ) {
        $a[\'rel\'] = \'nofollow\';
    } else {
        $a[\'rel\'] .= \' nofollow\';
    }
}

$author_desc = $dom->saveHTML();

$buffy .= $author_desc;
将问题中的原始代码替换为此答案中的代码(这基于您发布的完整代码here).

代码改编自this answer 堆栈溢出时。编码修复通过this post.