如何使用正则表达式在标记a上添加属性rel nofollow

时间:2017-05-08 07:33:05

标签: php regex rel

如何使用正则表达式

在标记a上添加属性rel nofollow

样品:

<a href="http://www.test.org/5521" rel="follow">test1</a>
<a href="http://www.test.org/5522" rel="external">test1</a>
<a href="http://www.test.org/5523">test1</a>

要:

<a href="http://www.test.org/5521" rel="nofollow">test1</a>
<a href="http://www.test.org/5522" rel="nofollow">test1</a>
<a href="http://www.test.org/5523" rel="nofollow">test1</a>

1 个答案:

答案 0 :(得分:1)

Step1:从标签a中删除所有Rel

$result = preg_replace('@rel="(.*)"@U', '', $html);

步骤2:在taf上添加Rel Nofollow

$result = preg_replace('@<a(.*)>@U', '<a$1 rel="nofollow">', $result);