how to add attribute rel nofollow on tag a with regex
Sample:
<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>
To:
<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>
Using a DOM parser would be a more natural solution here:
$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();
See the PHP demo
With $links = $dom->getElementsByTagName("a");
, you get all the a
nodes, and with $link->setAttribute('rel', 'nofollow');
, you set the rel
attribute regardless whether it was present or not.
Output:
<html><body>
<a href="http://www.test.org/5521" rel="nofollow">test1</a><br>
<a href="http://www.test.org/5522" rel="nofollow">test1</a><br>
<a href="http://www.test.org/5523" rel="nofollow">test1</a>
</body></html>
Step1: Remove All Rel from tag a
$result = preg_replace('@rel="(.*)"@U', '', $html);
Step2: Add Rel Nofollow on taf a
$result = preg_replace('@<a(.*)>@U', '<a$1 rel="nofollow">', $result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.