Match And Replace Text Not Within A Link

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;


I’m having a hard time understanding the goal. Can you post an example of the functions usage, as well as the missing function getRandomRelatedURL

Sponsor our Newsletter | Privacy Policy | Terms of Service