php截取字符串中的关键字,并高亮显示

<?php
$str = "hahaceshi测试一下关键字高亮显示,以及长字符串截取的问题!";
$key = "关键字";

$r = sub_key_h($str,$key);
echo $r;

function sub_key_h($str,$key,$len=10,$enc='utf-8'){
    $strlen = mb_strlen($str,$enc);
    $keylen = mb_strlen($key,$enc);
    $keypos = mb_strpos($str,$key,0,$enc);
    $leftpos = $keypos - 1;
    $rightpos = $keypos + $keylen;

    if($keylen > $len){
        return "<font style='font-color:red;'>".mb_substr($key,0,$len,$enc)."</font>...";
    }
    $result = "<font style='font-color:red;'>".$key."</font>";
    for($i = 0;$i<$len - $keylen;$i++){
        if($leftpos >= 0){
            $result = mb_substr($str,$leftpos--,1,$enc).$result;
        }else{
            $result .= mb_substr($str,$rightpos++,1,$enc);
        }
    }
    if($leftpos >= 0){
        $result = "...".$result;
    }
    if($rightpos < $strlen){
        $result .= "...";
    }
    return $result;
}
?>

结果为

...shi测试一下<font style='font-color:red;'>关键字</font>...

 

posted @ 2013-08-08 11:12  soj  阅读(834)  评论(0编辑  收藏  举报