简体   繁体   中英

php str_ireplace without losing case

is it possible to run str_ireplace without it destroying the original casing?

For instance:

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

this all works fine, but the result outputs:

[hello] How [are] You

instead of:

[Hello] How [Are] You

(square brackets being the color background)

Thanks.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM