I tried to change all links in a php string to nofollow etc. before they are posted to the mysql db.
Both lines I tried did not work:
$group_description = preg_replace('/\b<a href="\b/', '<a rel="nofollow" href="/out/out.php?url=', $group_description);
$group_description = str_replace('<a href="', '<a rel="nofollow" href="/out/out.php?url=', $group_description);
Both Result in: <a href="%5C%22http://www.website.net%5C%22">keyword</a>
You can use DomDocument to do this:
$html = '<a href="/foo">foo</a> <a href="/bar">bar</a>';
$dom = new DomDocument();
$dom->loadHTML($html);
$as = $dom->getElementsByTagName('a');
foreach($as as $a) {
$a->setAttribute('rel', 'nofollow');
$a->setAttribute('href', '/out/out.php?url=' . rawurlencode($a->getAttribute('href')));
}
$out = simplexml_import_dom($dom->getElementsByTagName('body')->item(0))->asXML();
$out = preg_replace('#<body>(.*)</body>#', "$1", $out);
echo $out;
I'm not thrilled with the last 3 lines, but that part mostly depends on how you want to use the final output, as a fragment, or a complete HTML document. The above pulls out a fragment, though there are likely better ways to do that. Otherwise you can just use $dom->asHTML();