3mr (3 means A!)

STR_REPLACE: Another Case Insensitive Replace

Posted by: Amr on: October 23, 2007

The str_replace function in PHP doesnt support strings with different case, and can’t match strings or find them as long as they have different cases..

Seems PHP.NET forgot to implement such function (for complex scripts and right to left languages); to match strings whatever the letter case is, anyhow, here is a function that will replace any string you want whatever the case is.

hope you benifit from..

function stri_replace($word,$replace,$str){
    $wordray = is_array($word) ? true : false;
    $replray = is_array($replace) ? true: false;
    if($wordray){
        $wordkeys = array_keys($word);
        $sizeword = count($wordkeys);
        if($replray){
            $replkeys = array_keys($replace);
            $sizerepl = count($replace);
        }
        for($i=0; $i<$sizeword; $i++){
            if($replray && array_key_exists($i,$replkeys)){
                $repll = $replace[$replkeys[$i]];
            }elseif($replray){
                $repll = ”;
            }else{
                $repll = $replace;
            }
            $str = stri_replace($word[$wordkeys[$i]],$repll,$str);
        }
        $ret = $str;
    }else{
        $str_low = strtolower($str);
        $word_low = strtolower($word);
        $str_low = str_replace($word_low,$word,$str_low);
        $explode = explode($word,$str_low);
        $count = count($explode);
        $ret = ”;
        $holder = 0;
        $len = strlen($word);
        for($i=0; $i<$count; $i++){
            $thislen = strlen($explode[$i]);
            $ret .= substr($str,$holder,$thislen);
            if($i !== ($count – 1)){
                $ret .= $replace;
            }
            $holder = $holder + $thislen + $len;
        }
    }
    return $ret;
}

5 Responses to "STR_REPLACE: Another Case Insensitive Replace"

It seems that you forgot to check str_ireplace function.

http://www.php.net/manual/en/function.str-ireplace.php

;)

Well Steve.. Thank you for your comment..

regarding the str_ireplace built-in function, it is not functional with special characters and the language we might use (such as Arabic).

str_replace and str_ireplace are not good for Arabic strings so i would prefer to use the above function for very accurate results.

anyway, thank you for confirming the availablity of the str_ireplace at PHP.net knowing that it is not working on my PHP5 installation (might be bug or text encoding problem..)

Bytheway, str_ireplace doesnt follow the naming convention of ( moduleName_functionName ) ;)

I tried str_ireplace built-in function which will work only if your running with PHP5.

Also it doesnt work with some charsets

Unexpected string error…in your script

Leave a Reply