Regexs HTML, PHP HTML-, .
nofollow, rel .
$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));
}
var_dump($dom->saveHTML());
CodePad.
HTML $dom->saveHTML(). , html, body .., , HTML...
$html = '';
foreach($dom->getElementsByTagName('body')->item(0)->childNodes as $element) {
$html .= $dom->saveXML($element, LIBXML_NOEMPTYTAG);
}
echo $html;
>= PHP 5.3, saveXML() saveHTML() .
HTML...
<a href="">hello</a>
<a href="" rel="">hello</a>
<a href="" rel="hello there">hello</a>
<a href="" rel="nofollow">hello</a>
... ...
<a href="" rel="nofollow">hello</a>
<a href="" rel="nofollow">hello</a>
<a href="" rel="hello there nofollow">hello</a>
<a href="" rel="nofollow">hello</a>