Skip to content

Instantly share code, notes, and snippets.

@alxfv
Created April 25, 2013 08:57
Show Gist options
  • Save alxfv/5458446 to your computer and use it in GitHub Desktop.
Save alxfv/5458446 to your computer and use it in GitHub Desktop.
Add attribute rel nofollow
<?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