gpt4 book ai didi

php str_ireplace 不丢失大小写

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:08:57 24 4
gpt4 key购买 nike

是否可以在不破坏原始外壳的情况下运行 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);

一切正常,但结果输出:

[hello] How [are] You

代替:

[Hello] How [Are] You

(方括号是彩色背景)

谢谢。

最佳答案

您可能正在寻找这个:

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

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

$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);

关于php str_ireplace 不丢失大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16740116/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com