str_ireplace() with keeping of case

Viewed 8744

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.

3 Answers

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