如何在不替换超链接 URL、图像标记 URL、图像标记标题和 alt 标记中找到的关键字的情况下替换字符串中所有出现的$keyword ?
例子:
$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>';
请注意,关键字“ sports ”与超链接 URL、图像标记 URL 以及图像标记标题和 alt 标记一起出现。
我想将 $keywords (sports) 替换为:
<span style="color: #000000; background-color: #FFFF00; font-weight: normal;">sports</span>
产生以下结果:
<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>
提前致谢。
编辑 - 附加信息
目前我正在使用以下两步方法,它仅适用于 URLs,而不适用于 title 和 alt 标签。我也不需要替换 title 和 alt 标签中的关键字。
// 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);
}