如发现替换字符串高亮显示的单词保持他们的情况下找到的单词

Tal*_*boY 1 php replace highlight

我想作为发现替换字符串高亮显示的单词保持自己的情况找到的单词.

$string1 = 'There are five colors';
$string2 = 'There are Five colors';

//replace five with highlighted five
$word='five';
$string1 = str_ireplace($word, '<span style="background:#ccc;">'.$word.'</span>', $string1);    
$string2 = str_ireplace($word, '<span style="background:#ccc;">'.$word.'</span>', $string2);

echo $string1.'<br>';
echo $string2;
Run Code Online (Sandbox Code Playgroud)

当前输出:

five颜色
five颜色

预期产量:

five颜色
Five颜色

怎么做到这一点?

Ama*_*ali 6

要突出一个字不区分大小写

使用preg_replace()以下正则表达式:

/\b($p)\b/i
Run Code Online (Sandbox Code Playgroud)

说明:

  • / - 开始分隔符
  • \b - 匹配单词边界
  • ( - 第一个捕获组的开始
  • $p - 逃跑的搜索字符串
  • ) - 第一次捕获组结束
  • \b - 匹配单词边界
  • / - 结束分隔符
  • i- 模式修饰符,使搜索不区分大小写

置换方式可以是<span style="background:#ccc;">$1</span>,在这里$1是一个反向引用-它会包含什么被第一个捕获组(在这种情况下,是被搜查的实际字)匹配

码:

$p = preg_quote($word, '/');  // The pattern to match

$string = preg_replace(
    "/\b($p)\b/i",
    '<span style="background:#ccc;">$1</span>', 
    $string
);
Run Code Online (Sandbox Code Playgroud)

看到它在行动


突出显示一组不区分大小写的单词

$words = array('five', 'colors', /* ... */);
$p = implode('|', array_map('preg_quote', $words));

$string = preg_replace(
    "/\b($p)\b/i", 
    '<span style="background:#ccc;">$1</span>', 
    $string
);

var_dump($string);
Run Code Online (Sandbox Code Playgroud)

看到它在行动