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;
}
October 24, 2007 at 6:58 pm
It seems that you forgot to check str_ireplace function.
http://www.php.net/manual/en/function.str-ireplace.php