i ja sam skoro radio to isto, pa evo moje verzije koja radi malo drugacije (ima dodatnu opciju da excludeuje neke domene, tako npr mozete lako da provucete ceo text kroz nju i samo na linkovima koje ne vode do vasih sajtova stavite nofollow):
PHP kôd:
class NoFollow {
private static $exceptions;
public static function add($text, $exceptions = array()) {
self::$exceptions = array();
foreach ($exceptions as $exception) {
if (!$exception) continue;
if ($exception[0] == '.') {
$exception = '([^.]+\.)?' . preg_quote(substr($exception, 1), '/');
} else {
$exception = preg_quote($exception, '/');
}
self::$exceptions[] = '/^(s?ftp|https?):\/\/' . $exception . '/i';
}
return preg_replace_callback('/<a\s+([^>]*)>/i', array(__CLASS__, 'filter'), $text);
}
private static function filter($matches) {
$attr = array();
if (preg_match_all('/([a-z0-9_:]+)\s*=\s*"([^"]*)"/i', $matches[1], $attribs)) {
foreach ($attribs[0] as $i => $attrib) {
$attr[$attribs[1][$i]] = $attribs[2][$i];
}
}
if (isset($attr['href'])) {
$external = true;
foreach (self::$exceptions as $exception) {
if (preg_match($exception, $attr['href'])) {
$external = false;
break;
}
}
if ($external) {
if (isset($attr['rel'])) {
if (strpos($attr['rel'], 'nofollow') === false) {
$attr['rel'] = 'nofollow ' . $attr['rel'];
}
} else {
$attr['rel'] = 'nofollow';
}
} elseif (isset($attr['rel']) and strpos($attr['rel'], 'nofollow') !== false) {
$attr['rel'] = trim(str_replace('nofollow', '', $attr['rel']));
if (empty($attr['rel'])) {
unset($attr['rel']);
}
}
}
$link = '<a';
foreach ($attr as $name => $value) {
$link .= " $name=\"$value\"";
}
return $link . '>';
}
}
koristi se jednostavno:
PHP kôd:
$text = NoFollow::add($text); // dodaje rel="nofollow" na sve linkove
$text = NoFollow::add($text, array('www.google.com')); // dodaje rel="nofollow" na sve linkove osim www.google.com (ali dodaje na npr code.google.com)
$text = NoFollow::add($text, array('.google.com')); // dodaje rel="nofollow" na sve linkove osim google.com (sa bilo kojim poddomenom, ili bez poddomena)