str_replace Case Sensitive Problem

When i use str_replace for replacement in PHP, it is changing without any case sensitive. Example i want to bold HousE, code is

<?
$text = "I like my house.";
$string = "HousE";
$text = str_replace($string,"<b>$string</b>",$text);
echo($text);
?>

Php 5 have another function to solve this problem str_ireplace() . But this is solve my problem exactly. Because i want to replace case sensitive to case sensitive.  I found this solution for my problem. I hope you’ll enjoy.


function ext_str_ireplace($findme, $replacewith, $subject)
{
     // Replaces $findme in $subject with $replacewith
     // Ignores the case and do keep the original capitalization by using $1 in $replacewith
     // Required: PHP 5

     $rest = $subject;
     $result = '';

     while (stripos($rest, $findme) !== false) {
          $pos = stripos($rest, $findme);

          // Remove the wanted string from $rest and append it to $result
          $result .= substr($rest, 0, $pos);
          $rest = substr($rest, $pos, strlen($rest)-$pos);

          // Remove the wanted string from $rest and place it correctly into $result
          $result .= str_replace('$1', substr($rest, 0, strlen($findme)), $replacewith);
          $rest = substr($rest, strlen($findme), strlen($rest)-strlen($findme));
     }

     // After the last match, append the rest
     $result .= $rest;

     return $result;
}
Share and Enjoy:
  • StumbleUpon
  • Digg
  • TwitThis
  • FriendFeed
  • del.icio.us
  • MySpace
  • Technorati
  • Facebook
  • Google Bookmarks
  • Live

Enjoy this article?

Consider subscribing to our RSS feed!

Share us Facebook, FriendFeed, Digg

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

1 Comment

  1. lluis
    18:36 on May 3rd, 2010

    Very thanks.

    str_ireplace works ok in php 5.

    Just it I needed

Sorry, the comment form is closed at this time.