php str_ireplace without losing case

后端 未结 3 930
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 06:53

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

For instance:

$txt = \"Hello How Are You\";
$a = \"are\";
$h = \"hello\         


        
相关标签:
3条回答
  • 2020-12-18 07:01

    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;
    }
    
    0 讨论(0)
  • 2020-12-18 07:12

    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);
    
    0 讨论(0)
  • 2020-12-18 07:12

    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;
    }
    
    0 讨论(0)
提交回复
热议问题