5

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'?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Haroldo
  • 36,607
  • 46
  • 127
  • 169

1 Answers1

2

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);
Narcis Radu
  • 2,519
  • 22
  • 33
  • 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 Jul 16 '10 at 08:54
  • Can you provide an example of your input string? Hard to build blind regexp :) – Narcis Radu Jul 16 '10 at 09:24
  • 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 Jul 16 '10 at 09:30