<?php $title='苏州园林 荷塘月色 古建筑 古色古香 房屋 走廊 建筑 阁楼 3d模型下载'; //用户搜索关键字 $so='超大城市 房屋 建筑 寺庙 绿地 花草村庄 古建筑 日式风格 3d模型下载'; //对用户的搜索词进行分词返回的结果 $str='[{"t":"超大","p":"0.649353"},{"t":"超大城市","p":"0.981573"},{"t":"大城","p":"0.46208"},{"t":"大城市","p":"0.855926"},{"t":"城市","p":"0.834678"},{"t":"房屋","p":"1"},{"t":"建筑","p":"1"},{"t":"寺庙","p":"1"},{"t":"绿地","p":"1"},{"t":"花草","p":"1"},{"t":"村庄","p":"1"},{"t":"古建","p":"0.282374"},{"t":"古建筑","p":"0.638011"},{"t":"建筑","p":"0.802111"},{"t":"日式","p":"0.639759"},{"t":"日式风格","p":"0.902741"},{"t":"风格","p":"0.82646"},{"t":"3d模型","p":"0.942089"},{"t":"模型","p":"0.74007"},{"t":"下载","p":"1"}]'; $aStr=json_decode($str,true); $temp1=temp2=$pxlst=[]; foreach ($aStr as $v){ $temp1[]=strlen($v['t']); $temp2[]=$v['t']; $pxlst[]=$v['t']; } //排序方便加高亮不重复 array_multisort($temp1,SORT_DESC,$pxlst); $title=preg_replace("/{$so}/i", "<b class='red'>{$so}</b>", $title); $glkwd=[]; foreach ($pxlst as $v){ //判断包含当前关键字是否已经高亮,高亮过的则跳过,否则就会出现高亮中嵌套高亮样式 if(searchIsInArr($glkwd,$v))continue; $title=preg_replace("/{$v}/i", "<b class='red'>{$v}</b>", $title); $glkwd[]=$v; } echo $title; //查找是否存在于数组内 function searchIsInArr($array,$keyword){ if(!$array)return false; $res=false; foreach($array as $key=>$values ){ if (strstr( $values , $keyword ) !== false ){ //说明找到了 $res=true; break; } } return $res; }
如果本文对你有帮助,欢迎打赏本站