help with regex - how can i make some urls no-follow?
Ok so i've made this function which works fine for converting most urls like pies.com or www.cakes.com to an actual link tag.
function render_hyperlinks($str){
$regex = '/(http:\/\/)?(www\.)?([a-zA-Z0-9\-_\.]+\.(com|co\.uk|org(\.uk)?|tv|biz|me)(\/[a-zA-Z0-9\-\._\?&=#\+;]+)*)/ie';
$str = preg_replace($regex,"'<a href=\"http://www.'.'$3'.'\" target=\"_blank\">'.strtolower('$3').'</a>'", $str);
return $str;
}
I would like to update this function to add no-follow
tags to links to my competitors,
so i would have certain keywords (competitor names) to nofollow for example if my site was about baking i might want to:
no-follow any sites with the phrases 'bakingbrothers', 'mr开发者_高级运维kipling', 'lyonscakes'
is it possible to implement this if(contains x){ add y}
into my regex?
is this what is called a 'lookback'?
Maybe preg_replace_callback is what you are looking for:
function link($matches)
{
$str_return = '<a href="http://www.'.$matches[3].'" target="_blank"';
if(in_array($matches[3], $no_follow_array))
{
$str_return .= ' no-follow';
}
$str_return .='>'.strtolower($matches[3]).'</a>';
}
$regex = '/(http:\/\/)?(www\.)?([a-zA-Z0-9\-_\.]+\.(com|co\.uk|org(\.uk)?|tv|biz|me)(\/[a-zA-Z0-9\-\._\?&=#\+;]+)*)/ie';
$str = preg_replace_callback($regex,'link', $str);
精彩评论