php 在一个字符串中查找关键字并加亮显示

2011-7-11 杜世伟

<?php
/*
 * Created on 2011-5-16
 * author 孤独求学人
 */
 /*
  * $word 要查看的字符串
  * $find_word 要查找的字符串
  * $color 默认的颜色
  * 返回加亮查找的字符串
  */
 function find_word($word,$find_word,$color='#ffff00'){
     if(is_array($find_word)){
         foreach($find_word as $k=>$new_word){
             $pattern[$k] = $new_word;
             $replace[$k] = "<font style='background-color:".$color.";'>\\1</font>";//\\1 符号来表示逆向引用
         }
     }else{
         $pattern = "/\b($find_word)\b/is";
         $replace = "<font style='background-color:".$color.";'>\\1</font>";//\\1 符号来表示逆向引用
     }
     //preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit])
     return preg_replace($pattern,$replace,$word);
 }
?>
<?
$str = "good study good up,good up";
$result = find_word($str,"good","#ff0000");
print_r($result);
?>

标签: php find_word preg_replace

Powered by emlog 沪ICP备2023034538号-1