str_ireplace() with keeping of case
$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);
Either replace with the exact word, or use preg_replace:
preg_replace('/(The)/i', "<strong>$1</strong>", $original);
I have written an alternative solution (a function which uses pure string replacement) to do the job, which allows you to easily set the prefix and suffix (for highlighting):
function replace_keep_case($st1, $find1) {/// set prefix and suffix here$prefix="<span style='color:red;'><b>";$suffix="</b></span>";$index=0;$resultstring=""; while ($index < strlen($st1)) { if (strtoupper(substr($st1, $index, strlen($find1)))==strtoupper($find1)) { $resultstring.=$prefix.substr($st1, $index, strlen($find1)). $suffix; $index=$index+strlen($find1); } else { $resultstring.=substr($st1, $index, 1); $index++; } } return $resultstring; }
For example:
$text="CHICHiOn Ichiro's Malt & Grain (Limited Edition) 700ml 48% CONDITION";$findstring="ion";echo replace_keep_case($text, $findstring);