Jump to content

Php Match And Replace Text Not Within A Link (Anchor Tag)


o3xa

Recommended Posts

I'm trying to create an auto linking functionality, The problem I have is that when a keyword has been linked or the text already contains a link then the title or text attributes of the anchor tag may get replaced.

So I don't want any anchor tag to be used in the match. I'm using a random keyword replacement so its not a case of just consecutively replacing them.

Here is the function I'm currently using:

 

function replace_n_occurences ($str, $search, $replace, $n) {


$foundRKW = 'na';


$replace = getRandomRelatedURL( $search, $foundRKW );


   // Get all occurences of $search and their offsets within the string


   $count = preg_match_all('/\b'.preg_quote($search, '/').'\b/', $str, $matches, PREG_OFFSET_CAPTURE);




   // Get string length information so we can account for replacement strings that are of a different length to the search string


   $searchLen = strlen($search);


   $diff = strlen($replace) - $searchLen;


   $offset = 0;



   // Loop $n random matches and replace them, if $n < 1 || $n > $count, replace all matches


   $toReplace = ($n < 1 || $n > $count) ? array_keys($matches[0]) : (array) array_rand($matches[0], $n);


   foreach ($toReplace as $match) {


       $str = substr($str, 0, $matches[0][$match][1] + $offset).$replace.substr($str, $matches[0][$match][1] + $searchLen + $offset);


       $offset += $diff;


   }


   return $str;
}

Why not just replace all of that with one preg_replace () call? If you want every replacement value to be random, you can use the preg_replace_eval (e) modifier.

No need to check that the same length is used either, as preg_replace () only overwrites what matches, and extends/shortens the string as necessary to accommodate the replacement value.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.