php str_ireplace without losing case

后端 未结 3 931
爱一瞬间的悲伤
爱一瞬间的悲伤 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:12

    You're probably looking for this:

    $txt = preg_replace("#\\b($a|$h)\\b#i", 
      "$1", $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, 
          "$1", $txt);
    

提交回复
热议问题