Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_ireplace() with keeping of case

How can I use str_ireplace (or something similar) to replace some text for formatting and then return it with the same caps?

Example:

$original="The quick red fox jumps over the lazy brown dog."; $find="thE";  print str_ireplace($find,'<b>'.$find.'</b>',$original); 

That will output: thE quick red fox jumps over the lazy brown dog.

I want it to keep the original case and only apply the formatting, in this example, bold text.

Thank you.

like image 240
Francisc Avatar asked Aug 15 '10 23:08

Francisc


2 Answers

$original = "The quick red fox jumps over the lazy brown dog."; $new = preg_replace("/the/i", "<b>\$0</b>", $original); 

gives "The quick red fox jumps over the lazy brown dog." If you want to match specific words, you can add word boundaries: preg_replace('/\bthe\b/i', ....

If you want to parameterize the replacement, you can use preg_quote:

 preg_replace('/\b' . preg_quote($word, "/") . '\b/i', "<b>\$0</b>", $original); 
like image 121
Artefacto Avatar answered Sep 20 '22 16:09

Artefacto


Either replace with the exact word, or use preg_replace:

preg_replace('/(The)/i', "<strong>$1</strong>", $original); 
like image 39
mhitza Avatar answered Sep 20 '22 16:09

mhitza