Php 如何使用regex添加属性rel nofollow-on标记a
如何使用regex添加属性rel nofollow-on标记a 样本:Php 如何使用regex添加属性rel nofollow-on标记a,php,regex,rel,Php,Regex,Rel,如何使用regex添加属性rel nofollow-on标记a 样本: <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> 致: 步骤1:从标记a中
<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>
致:
步骤1:从标记a中删除所有Rel
$result = preg_replace('@rel="(.*)"@U', '', $html);
步骤2:在taf a上添加Rel Nofollow
$result = preg_replace('@<a(.*)>@U', '<a$1 rel="nofollow">', $result);
$result=preg_replace('@@U',''$result);
步骤1:从标记a中删除所有Rel
$result = preg_replace('@rel="(.*)"@U', '', $html);
步骤2:在taf a上添加Rel Nofollow
$result = preg_replace('@<a(.*)>@U', '<a$1 rel="nofollow">', $result);
$result=preg_replace('@@U',''$result);
在这里,使用DOM解析器将是一个更自然的解决方案:
$html = <<<STR
<html><body>
<a href="http://www.test.org/5521" rel="follow">test1</a><br/>
<a href="http://www.test.org/5522" rel="external">test1</a><br/>
<a href="http://www.test.org/5523">test1</a>
</body></html>
STR;
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$links = $dom->getElementsByTagName("a");
foreach($links as $link) {
$link->setAttribute('rel', 'nofollow');
}
echo $dom->saveHTML();
在这里,使用DOM解析器将是更自然的解决方案:
$html = <<<STR
<html><body>
<a href="http://www.test.org/5521" rel="follow">test1</a><br/>
<a href="http://www.test.org/5522" rel="external">test1</a><br/>
<a href="http://www.test.org/5523">test1</a>
</body></html>
STR;
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$links = $dom->getElementsByTagName("a");
foreach($links as $link) {
$link->setAttribute('rel', 'nofollow');
}
echo $dom->saveHTML();
为什么不使用DOM?为什么不使用DOM?