7

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

(方括号是颜色背景)

谢谢。

4

3 回答 3

7

你可能正在寻找这个:

$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);
于 2013-05-24T17:07:10.080 回答
4

我想你会想要一些类似的东西:找到显示的单词,然后用它来进行替换。

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;
}
于 2013-05-24T17:19:10.693 回答
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;
}
于 2013-05-24T17:14:32.253 回答