是否可以在不破坏原始外壳的情况下运行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
(方括号是颜色背景)
感谢。
答案 0 :(得分:4)
你可能正在寻找这个:
$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);
答案 1 :(得分:2)
我认为你需要这些内容:找到显示的单词,然后使用它来进行替换。
function highlight($word, $text) {
$word_to_highlight = substr($text, stripos($text, $word), strlen($word));
$text = str_ireplace($word, "<span style='background-color:#EEEE00'>".$word_to_highlight."</span>", $text);
return $text;
}
答案 2 :(得分:1)
不漂亮,但应该有效。
function str_replace_alt($search,$replace,$string)
{
$uppercase_search = strtoupper($search);
$titleCase_search = ucwords($search);
$lowercase_replace = strtolower($replace);
$uppercase_replace = strtoupper($replace);
$titleCase_replace = ucwords($replace);
$string = str_replace($uppercase_search,$uppercase_replace,$string);
$string = str_replace($titleCase_search,$titleCase_replace,$string);
$string = str_ireplace($search,$lowercase_replace,$string);
return $string;
}