Jump to content

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


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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.