• PHP Help PHP Coding
  • Using preg_replace to add rel="nofollow" to a link based if its not the local domain?

I am trying to use preg_replace to add rel="nofollow" to a link and am having a difficult time with it due to my regexp abilities. The way I am currently doing it is i read the string into a variable and then explode with <a href=. I then compare each array element for whether or not it contains my domain and if it does not then i do the preg replace. I am sure there is an easier way of doing it, but I do not know how. Can i just use a regexp in preg_replace to conver the string if and only if the domain portion does not match a certain string?

Here is my code which does not work:

$search = array ('/"(\S+)"(.+)</a>/' );

$replace = array ('"$1" rel="nofollow" $2</a>'); 

$done[$count] =  preg_replace($search,$replace,$value);

I am using an array as after I get this to work I will be doing more substitutions.

Any suggestions as to why this does not work?

    Use preg_replace_callback to find all <a> tags in the text, passing the matches to a function that looks at any href= attribute to see if it starts with a scheme name - "http:", probably - and if it has one, and the host it names isn't your own, inserts the attribute and returns the whole thing.

    What profile is this, incidentally? I'm just wondering what a "nofollow" rel is supposed to do in this context.

      Write a Reply...