Jump to content

replace array problem


stevehossy

Recommended Posts

Heres example

$code_entities_match =

array('a','b');

$code_entities_replace =

array('cb','de');

 

If i type ab i want it to be cbde... but, because when cb replaces a, theres a b, and the b gets replaced to de. so if you dont understand, i want the outcome of this to be cbde, but it turns out to be cde. how can i fix this?

Link to comment
https://forums.phpfreaks.com/topic/149576-replace-array-problem/
Share on other sites

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);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.