php str_ireplace without losing case

落爺英雄遲暮 提交于 2019-11-29 08:00:40

You're probably looking for this:

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

... or, if you want to highlight the whole array of words (being able to use metacharacters as well):

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

I think you'd want something along these lines: Find the word as it is displayed, then use that to do the replace.

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;
}
user1122069

Not beautiful, but should work.

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!