Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用regex添加属性rel nofollow-on标记a_Php_Regex_Rel - Fatal编程技术网

Php 如何使用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中

如何使用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中删除所有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?