How can I replace all the occurrences of the $keyword within a string without replacing the keywords found within the hyperlink URLs, image tag URLs, image tag title and alt tags?
Example:
$keywords = 'sports';
$string = '<a href="http://my_domain_name.com/sports/info.php"><img class="icon" src="http://my_domain_name.com/sports/images/football.gif" title="Get the latest football sports news" alt="Get the latest football sports news" />Football sports news</a>';
Notice that the keyword 'sports' appears with the hyperlink URL, images tag URL, and image tag title and alt tags.
I want to replace $keywords (sports) with:
<span style="color: #000000; background-color: #FFFF00; font-weight: normal;">sports</span>
to yeild the following results:
<a href="http://my_domain_name.com/sports/info.php"><img class="icon" src="http://my_domain_name.com/sports/images/football.gif" title="Get the latest football sports news" alt="Get the latest football sports news" />Football <span style="color: #000000; background-color: #FFFF00; font-weight: normal;">sports</span> news</a>
Thanks in advance.
EDIT - Additional Information
Currently I am using the following 2-step method and it works for just the URLs, and not the title and alt tags. I also need to not replace the keywords in the title and alt tags too.
// Replaces both the website and general images path urls with character strings (used to prevent highlighting keywords found within the path urls)
if(strpos('http://my_domain_name.com/sports', $keywords) != false) {
$description = str_ireplace('http://my_domain_name.com/sports', '1q2w3e4r5t6y7u', $description);
}
if(strpos('http://my_domain_name.com/sports/images', $keywords) != false) {
$description = str_ireplace('http://my_domain_name.com/sports/images', '7u6y5t4r3e2w1q', $description);
}
// Highlights the Search Keywords
$description = str_ireplace($keywords, '<span style="color: #000000; background-color: #FFFF00; font-weight: normal;">'.$keywords.'</span>', $description);
// Replaces the character strings with the website and general images path urls
if(strpos('http://my_domain_name.com/sports', $keywords) != false) {
$description = str_ireplace('1q2w3e4r5t6y7u', 'http://my_domain_name.com/sports', $description);
}
if(strpos('http://my_domain_name.com/sports/images', $keywords) != false) {
$description = str_ireplace('7u6y5t4r3e2w1q', 'http://my_domain_name.com/sports/images', $description);
}