选择<a> tags from databse and add rel=&#34;nofollow&#34;

时间:2017-05-22 15:49:24

标签: php mysql regex select

I am not sure how to implement the following:

I have a database table "Posts" contains ID, Content, I have more than 20000 Posts in the Posts table, I would like to make mysql query to find all external tags inside the Content record that don't have rel="nofollow" attribute, and then add rel="nofollow" and update the post.

Any suggestions on how to implement this?

1 个答案:

答案 0 :(得分:0)

我在Stackoverflow上找到了这个解决方案,找不到对不起的参考。它对我有用。

$content = nofollow($content,'example.com');
function nofollow($html, $skip = null) {
    return preg_replace_callback(
        "#(<a[^>]+?)>#is", function ($mach) use ($skip) {
            return (

                !($skip && strpos($mach[1], $skip) !== false) &&
                strpos($mach[1], 'rel=') === false
            ) ? $mach[1] . ' rel="nofollow">' : $mach[0];
        },
        $html
    );
}