用于搜索结果的关键字高亮显示(不区分大小写)

在搜索结果的显示中,我们通常要把关键字高亮,对于中文,直接用strtr把关键字替换成加<font color=red><b>关键字</b></font>就可以了。

但对于英文,存在大小写的问题,比如用户搜iphone,我们需要把结果中的iPhone/IPHONE之类的单词都要高亮;简单的用strtr直接替换就不行了。

下面是自己写的一个函数:



<?php
//搜索结果,要高亮替换的文字,如文章标题等(为演示效果,选的字符串比较乱)
$str = "sdfdiphoneabIPHoNEipHONE";
//搜索关键字
$key_arr = array("fd","iphone");
//返回高亮结果
echo highlight($str,$key_arr);

function highlight($str,$key_arr)
{
$param_temp = array();
preg_match_all('/'.join('|',$key_arr).'/i',$str,$matches);

foreach($matches[0] as $value)
{
$param_temp[$value] = "<font color=red><b>".$value ."</b></font>";
}

$str2 = strtr($str,$param_temp);
return $str2;
}



( ! ) Warning: Missing argument 1 for cwppos_show_review(), called in /data/www/enjoyphp/wp-content/themes/flat/content-single.php on line 29 and defined in /data/www/enjoyphp/wp-content/plugins/wp-product-review/includes/legacy.php on line 18
Call Stack
#TimeMemoryFunctionLocation
10.0000354840{main}( ).../index.php:0
20.0000355128require( '/data/www/enjoyphp/wp-blog-header.php' ).../index.php:17
30.102510159832require_once( '/data/www/enjoyphp/wp-includes/template-loader.php' ).../wp-blog-header.php:19
40.103310230976include( '/data/www/enjoyphp/wp-content/themes/flat/single.php' ).../template-loader.php:74
50.156210828992get_template_part( ).../single.php:5
60.156210829512locate_template( ).../general-template.php:167
70.156210829608load_template( ).../template.php:643
80.156210829992require( '/data/www/enjoyphp/wp-content/themes/flat/content-single.php' ).../template.php:686
90.159510815104cwppos_show_review( ).../content-single.php:29

发表评论

电子邮件地址不会被公开。 必填项已用*标注