tags:

views:

59

answers:

1

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', 'mrkipling', 'lyonscakes'

is it possible to implement this if(contains x){ add y} into my regex?

is this what is called a 'lookback'?

+1  A: 

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);
narcisradu
this looks great however i'm having trouble with characters, it seems preg_replace_callback doesn't accept the 'e' modifier, so now it is capturing the 'n' form '\n' new lines?
Haroldo
Can you provide an example of your input string? Hard to build blind regexp :)
narcisradu
ah it was my mistake, i was double escaping the linebreaks, your solution works fantastically, and thank you also to Marty for his help too
Haroldo
You are welcome :)
MartyIX