stevehossy Posted March 15, 2009 Share Posted March 15, 2009 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? Quote Link to comment https://forums.phpfreaks.com/topic/149576-replace-array-problem/ Share on other sites More sharing options...
Mark Baker Posted March 16, 2009 Share Posted March 16, 2009 $code_entities_match = array('b','a'); $code_entities_replace = array('de','cb'); Quote Link to comment https://forums.phpfreaks.com/topic/149576-replace-array-problem/#findComment-785723 Share on other sites More sharing options...
sasa Posted March 16, 2009 Share Posted March 16, 2009 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); ?> Quote Link to comment https://forums.phpfreaks.com/topic/149576-replace-array-problem/#findComment-785752 Share on other sites More sharing options...
sasa Posted March 16, 2009 Share Posted March 16, 2009 oh i forget to add last part of the text please change return $out; to return $out.$text; Quote Link to comment https://forums.phpfreaks.com/topic/149576-replace-array-problem/#findComment-785913 Share on other sites More sharing options...
stevehossy Posted March 17, 2009 Author Share Posted March 17, 2009 sasa thats exactly what i needed.. Thank you! Quote Link to comment https://forums.phpfreaks.com/topic/149576-replace-array-problem/#findComment-786441 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.