Results 1 to 2 of 2

Thread: PHP match and replace text not within a link (anchor tag)

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Apr 2012
    Posts
    20

    PHP match and replace text not within a link (anchor tag)

    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:

    PHP Code:
    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$matchesPREG_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 || $n $count) ? array_keys($matches[0]) : (array) array_rand($matches[0], $n);

        foreach (
    $toReplace as $match) {

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

            
    $offset += $diff;

        }

        return 
    $str;


  2. #2
    Addicted Member
    Join Date
    Dec 2007
    Posts
    186

    Re: PHP match and replace text not within a link (anchor tag)

    Not quite sure what you are asking, can you provide an example of the "text" and an example of what should and shouldn't be matched.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width