php - How to add rel="nofollow" to links with preg_replace() -
the function below designed apply rel="nofollow" attributes external links , no internal links unless path matches predefined root url defined $my_folder below.
so given variables...
$my_folder = 'http://localhost/mytest/go/'; $blog_url = 'http://localhost/mytest'; and content...
<a href="http://localhost/mytest/">internal</a> <a href="http://localhost/mytest/go/hostgator">internal cloaked link</a> <a href="http://cnn.com">external</a> the end result, after replacement should be...
<a href="http://localhost/mytest/">internal</a> <a href="http://localhost/mytest/go/hostgator" rel="nofollow">internal cloaked link</a> <a href="http://cnn.com" rel="nofollow">external</a> notice first link not altered, since internal link.
the link on second line internal link, since matches our $my_folder string, gets nofollow too.
the third link easiest, since not match blog_url, external link.
however, in script below, of links getting nofollow. how can fix script want?
function save_rseo_nofollow($content) { $my_folder = $rseo['nofollow_folder']; $blog_url = get_bloginfo('url'); preg_match_all('~<a.*>~isu',$content["post_content"],$matches); ( $i = 0; $i <= sizeof($matches[0]); $i++){ if ( !preg_match( '~nofollow~is',$matches[0][$i]) && (preg_match('~' . $my_folder . '~', $matches[0][$i]) || !preg_match( '~'.$blog_url.'~',$matches[0][$i]))){ $result = trim($matches[0][$i],">"); $result .= ' rel="nofollow">'; $content["post_content"] = str_replace($matches[0][$i], $result, $content["post_content"]); } } return $content; }
try make more readable first, , afterwards make if rules more complex:
function save_rseo_nofollow($content) { $content["post_content"] = preg_replace_callback('~<(a\s[^>]+)>~isu', "cb2", $content["post_content"]); return $content; } function cb2($match) { list($original, $tag) = $match; // regex match groups $my_folder = "/hostgator"; // re-add quirky config here $blog_url = "http://localhost/"; if (strpos($tag, "nofollow")) { return $original; } elseif (strpos($tag, $blog_url) && (!$my_folder || !strpos($tag, $my_folder))) { return $original; } else { return "<$tag rel='nofollow'>"; } } gives following output:
[post_content] => <a href="http://localhost/mytest/">internal</a> <a href="http://localhost/mytest/go/hostgator" rel=nofollow>internal cloaked link</a> <a href="http://cnn.com" rel=nofollow>external</a> the problem in original code might have been $rseo wasn't declared anywhere.
Comments
Post a Comment