Created
April 25, 2013 08:57
-
-
Save alxfv/5458446 to your computer and use it in GitHub Desktop.
Add attribute rel nofollow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$str = '<!doctype html> | |
<html lang="en-US"> | |
<head> | |
<meta charset="UTF-8"> | |
<title></title> | |
</head> | |
<body> | |
<a href="http://km.ru">test</a> | |
</body> | |
</html>'; | |
echo htmlspecialchars($str) . '<br>'; | |
$dom = new DOMDocument; | |
$dom->loadHTML($str); | |
$anchors = $dom->getElementsByTagName('a'); | |
foreach($anchors as $anchor) { | |
$rel = array(); | |
if ($anchor->hasAttribute('rel') AND ($relAtt = $anchor->getAttribute('rel')) !== '') { | |
$rel = preg_split('/\s+/', trim($relAtt)); | |
} | |
if (in_array('nofollow', $rel)) { | |
continue; | |
} | |
$rel[] = 'nofollow'; | |
$anchor->setAttribute('rel', implode(' ', $rel)); | |
} | |
$str = $dom->saveHTML(); | |
echo htmlspecialchars($str); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment