PHP怎么給文字內(nèi)容中的關(guān)鍵字進行標紅,高亮處理?
How to highlight keywords in text content in PHP? -PHP Chinese website Q&A-How to mark and highlight keywords in text content in PHP? -PHP Chinese website Q&A
Let’s take a look and learn.
有些時候我們在顯示一篇文章的時候,可能需要把某些關(guān)鍵字進行標紅,高亮顯示,以便我們能快速的查找和定位這些關(guān)鍵字,下面讓我們看看具體實現(xiàn)的代碼。
/** ??*?關(guān)鍵字套紅方法 ??*? ??*?@access?public ??*?@param?array?$options?參數(shù)數(shù)組 ??*??<li>?$info_arr??array??內(nèi)容</li> ??*??<li>?$search_arr?array??關(guān)鍵詞數(shù)組?</li> ??*?@return?int?or?array ??*/ ??function?set_arr_keyword_red($info_arr,?$search_arr) ?{ ??foreach?($search_arr?as?$search_str) ??{ ???foreach?($info_arr?as?$key?=>?$info) ???{ ????if(in_array($key,array('item_title','keywords',?'photo_title',?'photo_site','content',))) ????{ ?????$info?=?strip_tags($info); ?????$info?=?str_replace('?',?'',?$info); ?????$q_str_pos?=?stripos($info,?$search_str); ?????if?(false!==$q_str_pos) ?????{ ??????$info?=?csubstr($info,?$q_str_pos+150); ??????$temp?=?csubstr($info,$q_str_pos-150); ??????$info?=?substr($info,?strlen($temp),?300); ??????$info?=?preg_replace("/{$search_str}/i",?"<font?color='red'>{$search_str}</font>",?$info); ? ??????if($info_arr['match_key']=='') ??????$info_arr['match_key']?=?$key; ?????} ?????else ?????{ ??????$info?=?csubstr($info,300); ?????} ????} ????$info_arr[$key]?=?$info; ???} ??} ??return?$info_arr; ?} ? $str?=?'woloveu小君'; $info_arr?=?array('photo_title'?=>?'womejiojd我們都圍毆防靜低屁啊小君雞凍啊泡腳盆大'); $search_arr?=?array('小君'); $ret?=?set_arr_keyword_red($info_arr,?$search_arr); dump($ret?);