本文介绍了php str_ireplace,不丢失大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不破坏原始大小写的情况下运行str_ireplace?

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

例如:

$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

代替:

[Hello] How [Are] You

(方括号是彩色背景)

谢谢.

推荐答案

您可能正在寻找:

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

这篇关于php str_ireplace,不丢失大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 12:51