38

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 3

50
$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);
2
  • *The quick brown fox jumps over the lazy dog
    – Popnoodles
    Apr 2, 2014 at 1:18
  • 1
    Add u modifier for UTF-8 support Apr 6, 2021 at 15:15
4

Either replace with the exact word, or use preg_replace:

preg_replace('/(The)/i', "<strong>$1</strong>", $original);
0
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.