Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.