Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 830
FoxyFish Avatar asked May 24 '13 17:05

FoxyFish


3 Answers

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);
like image 200
raina77ow Avatar answered Sep 23 '22 13:09

raina77ow


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;
}
like image 34
mhanson01 Avatar answered Sep 21 '22 13:09

mhanson01


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;
}
like image 35
user1122069 Avatar answered Sep 20 '22 13:09

user1122069