<?php
function setKeyWords($str,$word_arr=array()){
// 设置多字节字符内部编码为utf8
mb_internal_encoding("UTF-8");
// 创建一个跟字符串长度一致的数组,用0填充
$map=array_fill(0,mb_strlen($str),0);
// 遍历关键词数组,将关键词对应的map数组的位置上的数字置为1
foreach ($word_arr as $value) {
$pos=-1;
$pos_count=0;
$pos_arr=array();
// 如果找到了这个关键词,就将这个词的位置存入位置数组中(来支持多次出现此关键词的情况)
while(($pos=mb_strpos($str,$value,$pos+1))!==false){
$pos_arr[]=$pos;
$pos_count++;
}
// 遍历数组,将对应位置置1
foreach ($pos_arr as $pos_val) {
if($pos_val!==false){
$fill=array_fill($pos_val,mb_strlen($value),1);
$map = array_replace($map,$fill);
}
}
$pos=null;
}
// 遍历map数组,加入高亮代码
$flag=0;
$position=-1;
$result=""; // 结果数组
foreach ($map as $key => $value) {
if($value==1){
// 如果第一次出现1,则加上html标签头
if($flag==0) $result.="<span class=\"fc-red\">";
$flag=1;
}else{
// 如果已经到了一个0,但上一个还是1时,加入html标签尾
if($flag==1){
$position=$key-1;
$flag=0;
$result.="</span>";
}
}
// 将该位置的字符加入结果字符串中
$result.=mb_substr($str,$key,1);
}
return $result;
}
$title="服务服务员";
$arr=array("服务员","服务");
echo setKeyWords($title,$arr);
- Output for 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.24 - 5.5.35, 5.6.8 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.25, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
- <span class="fc-red">服务服务员
- Output for 5.0.0 - 5.0.5, 5.1.0 - 5.1.6, 5.2.0 - 5.2.17
- Fatal error: Call to undefined function array_replace() in /in/A7UZm on line 21
Process exited with code 255. - Output for 4.4.5 - 4.4.9
- Fatal error: Call to undefined function: array_replace() in /in/A7UZm on line 21
Process exited with code 255. - Output for 4.3.2 - 4.3.11, 4.4.0 - 4.4.4
- Fatal error: Call to undefined function: array_replace() in /in/A7UZm on line 21
Process exited with code 255. - Output for 4.3.0 - 4.3.1
- Fatal error: Call to undefined function: array_replace() in /in/A7UZm on line 21
preferences:
234.61 ms | 401 KiB | 325 Q