
Using arrays in string replacement...
Quote:
> $test = array('MAMA' => 'papa',
> 'SISTER' => 'brother');
> I want this array to be used for replaceing inside a string, the case
shouldn't matter but
Quote:
> it should adopt the case of the source (so replace Mama by Papa and
SiStEr by BrOtHer).
> I'm not sure how to start without using a loop which would make the script
slow...
> --
> www.wazzoo.net
It is not pretty, but it works:
<?
$test = array('MAMA' => 'papa', 'SISTER' => 'brother', 'SIBLING' =>
'ancestor','GRANDMOTHER'=>'Aunt');
$string = "Mama loves Sister like SibLing loves Grandmother" ;
foreach ($test as $key => $value) {
if (eregi($key, $string, $match)) {
$repl = "" ;
for ($i = 0; $i < strlen($match[0]); $i++) {
$char = $match[0][$i] ;
if ($match[0][$i] == strtolower($char)) {
$repl .= strtolower($test[$key][$i]) ;
} else if ($match[0][$i] == strtoupper($char)) {
$repl .= strtoupper($test[$key][$i]) ;
} else {
$repl .= $test[$key][$i] ;
}
}
$repl = strlen($test[$key]) > strlen($repl) ?
$repl.substr($test[$key],strlen($repl)) : $repl ;
$string = str_replace($match[0],$repl, $string) ;
}
Quote:
}
echo $string ;
?>
HTH
Regards, JW