How to replace keywords to link in WordPress without affecting keywords in alt attribute

I was trying to replace keywords in post content to links, however, I realise the keywords in alt attribute of img tag was also affected.
Is there solution for that? BTW, the code I was using in functions.php:

function replace_text_wp($text){  
$replace = array(  
    'keyword1' => '<a href="http://demo.com/" rel="bookmark" title="keyword1">keyword1</a>',  
);  
$text = str_replace(array_keys($replace), $replace, $text);  
return $text;  

}

Read More

add_filter(‘the_content’, ‘replace_text_wp’);

Related posts

Leave a Reply

1 comment

  1. I had to do something similar not too long ago, try this as your function – it might well need some fiddling and tweaking as I am adapting it to your example without testing

    function replace_text_wp($the_content){  
        //Break up the content into parts - allowing us to just edit content and not tags
        $parts = preg_split('/(<(?:[^"'>]|"[^"<]*"|'[^'<]*')*>)/', $the_content, -1, PREG_SPLIT_DELIM_CAPTURE);
        // Loop through the blocks and just edit the content
        for ($i=0, $n=count($parts); $i<$n; $i+=2) {
          // Check if any of our keywords are within the content
            // If so then make the keywords a link
            $parts[$i] = str_replace('keyword1', '<a href="http://demo.com/" rel="bookmark" title="keyword1">keyword1</a>', $parts[$i]);
          }
        }
        // Now put it all back together
        $the_content = implode('', $parts);
        return $the_content;
    }