PHP Snippets
stri_replace
Information
(PHP Version >= 4.10)Functions used in this snippet: array_key_exists, count, is_array, array_keys, strtolower, str_replace, explode, strlen, substr.
Description
str stri_replace(mixed search, mixed replace, str subject)
replaces all occurances of search with replace in the subject string and returns the corrected string. It is done without regards to text case.
search and replace can bot be arrays.
Snippet
<?php
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;
}
?>
Example
stri_replace Can be used in the following way:
<?php
$str = 'I HAte Red and love Blue';
echo stri_replace('hate','despise',$str); // I despise Red and love Blue
echo stri_replace(array('hate','LOVE'), array('enjoy','despise'),$str);
// I enjoy Red and despise Blue
?>
Updated on Jun 25th at 1 am.
1 Response to stri_replace
You could also do something with preg_replace with the case insensative modifier, but this was more fun for me.