Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

preg replace - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...