php给一组指定关键词添加span标签的方法
本文实例讲述了php给一组指定关键词添加span标签的方法。分享给大家供大家参考。具体如下:
这里是php给一组指定的关键词添加span标签,高亮突出显示关键词
//Exampleuse:$spanned=codeWords($string_containing_keywords); //Mysite:andrew.dx.am //Usingcolour==blue,butdifferentarraysofwordsanddifferent //colourscanbeadded. functiononlyWholeWords(&$value,$key){ //Ignoreswordsafter//commentdelimiters. //$value="/\b(".$value.")\b/";//doesn'thandlecomments //$value="/^(?:(?!\/\/).)*\K\b(".$value.")\b/"; //\KlookbehindalternativeisnotsupportedinPHP<5.2.4,souse: $value="/^((?:(?!\/\/).)*)\b".$value."\b/"; } functionaddSpan(&$value,$key,$color='blue'){ $value="$1<spanstyle='color:$color'>".$value."</span>"; } functioncodeWords($code){ $keywords=array('as','break','case','class', 'continue','default','do','elif','else', 'elseif','for','foreach','function','if', 'new','null','return','self','switch', 'this','to','typeof','until', 'var','void','while','with'); $keywords2=$keywords; array_walk($keywords,'onlyWholeWords'); array_walk($keywords2,'addSpan','blue'); $code=preg_replace($keywords,$keywords2,$code); return$code; }
希望本文所述对大家的php程序设计有所帮助。