try
<?php
$test = 'xabahb';
$code_entities_match = array('a','b');
$code_entities_replace = array('cb','de');
function my_replace($match, $replace, $text){
$out = '';
$test = false;
foreach ($match as $k => $m){
$x[$replace[$k]]= $m;
if (strpos($text, $m) !== false) {
$pos[$replace[$k]] = strpos($text, $m);
$test = true;
}
}
while ($test){
$p = min($pos);
$m = array_search($p, $pos);
$out .= substr($text,0,$p). $m;
$text = substr($text, $p+strlen($x[$m]));
$test = false;
foreach ($match as $k => $m){
if (strpos($text, $m) !== false) {
$pos[$replace[$k]] = strpos($text, $m);
$test = true;
} else unset($pos[$replace[$k]]);
}
}
return $out;
}
echo my_replace($code_entities_match, $code_entities_replace, $test);
?>