o3xa Posted November 29, 2012 Share Posted November 29, 2012 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; } Quote Link to comment https://forums.phpfreaks.com/topic/271324-php-match-and-replace-text-not-within-a-link-anchor-tag/ Share on other sites More sharing options...
Christian F. Posted November 29, 2012 Share Posted November 29, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/271324-php-match-and-replace-text-not-within-a-link-anchor-tag/#findComment-1396074 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.