php str_ireplace,不丢失大小写

Fox*_*ish 4 php preg-replace str-replace

是否可以在不破坏原始外壳的情况下运行str_ireplace?

例如:

$txt = "Hello How Are You";
$a = "are";
$h = "hello";
$txt = str_ireplace($a, "<span style='background-color:#EEEE00'>".$a."</span>", $txt);
$txt = str_ireplace($h, "<span style='background-color:#EEEE00'>".$h."</span>", $txt);
Run Code Online (Sandbox Code Playgroud)

一切正常,但是结果输出:

[hello] How [are] You
Run Code Online (Sandbox Code Playgroud)

代替:

[Hello] How [Are] You
Run Code Online (Sandbox Code Playgroud)

(方括号为彩色背景)

谢谢。

rai*_*7ow 5

您可能正在寻找:

$txt = preg_replace("#\\b($a|$h)\\b#i", 
  "<span style='background-color:#EEEE00'>$1</span>", $txt);
Run Code Online (Sandbox Code Playgroud)

...或者,如果您想突出显示整个单词数组(也可以使用元字符):

$txt = 'Hi! How are you doing? Have some stars: * * *!';
$array_of_words = array('Hi!', 'stars', '*');

$pattern = '#(?<=^|\W)(' 
       . implode('|', array_map('preg_quote', $array_of_words))
       . ')(?=$|\W)#i';

echo preg_replace($pattern, 
      "<span style='background-color:#EEEE00'>$1</span>", $txt);
Run Code Online (Sandbox Code Playgroud)