Scripts
advanced str_replace
Ik kwam van de week een probleem tegen met het gebruiken van arrays in de str_replace functie voor de te vervangen items, en de string waardoor het vervangen wordt. Zo wordt micro/combi (afkorting voor microwave/combination, combimagnetron in het nederlands) wanneer je een array hebt voor de te vervangen items (micro/combi en micro) dubbel vervangen: Dit toepassen op de str_replace zal microwavewave/combination terug geven. Eerst wordt 'micro/combi' vervangen door 'microwave/combination' en daarna wordt 'micro' uit het nieuwe woord ook nog eens vervangen door 'microwave'. Dit is natuurlijk niet de bedoeling, je krijgt zo wel heel rare namen voor de apparaten. Daarvoor heb ik de onderstaande functie geschreven.
advanced-strreplace
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
/**
* @author Robert Deiman
* @copyright 2008
* @param $aToreplace Array This array contains the items to replace
* @param $aReplacewith Array This array contains the items that are the replacements
* @param $sReplacestring String This string needs to be the text that the replacements need to be used for
* @param $bReplacewords Boolean Set to true if you're having problems with replacements (strange results)
*/
function array_replace($aToreplace, $aReplacewith, $sReplacestring, $bReplacewords = true){
//first we need to order both the arrays for replacement in the right order, to prevent mistakes
//that means the arrays must keep the same keys for the item to replace, and to replace it with
array_multisort($aToreplace,$aReplacewith);
rsort($aReplacewith);
rsort($aToreplace);
//if it's not needed to strictly use one item, because no strange results appear
if(!$bReplacewords){
//just use str_replace
$sReturnvalue = str_replace($aToreplace,$aReplacewith,$sReplacestring);
}
//you get weird results, so try this other option
else{
//walk thru each item that needs replacement
foreach($aToreplace as $sReplaceKey => $sReplaceValue){
//check if the item that needs replacement is 100% the same
if($sReplaceValue == $sReplacestring){
$sReturnvalue = str_replace($sReplaceValue,$aReplacewith[$sReplaceKey],$sReplacestring);
break;
}
}
}
return $sReturnvalue;
}
/* UNDERNEATH THIS IS ONLY FOR EXAMPLE, NOT PART OF THE FUNCTION */
$sStartitem = 'micro/combi';
$aReplaceitems= array('micro/combi','micro');
$aReplacewith=array('microwave/combination','microwave');
//use of the standard str_replace function will return microwavewave/combination
echo str_replace($aReplaceitems,$aReplacewith,$sStartitem).'<br />';
//use of the array_replace funtion in it's standard settings will just return microwave/combination
echo array_replace($aReplaceitems,$aReplacewith,$sStartitem).'<br />';
//use of the array_replace function with the $bReplacewords set to false will also return microwavewave combination
echo array_replace($aReplaceitems,$aReplacewith,$sStartitem,false).'<br />';
?>
Reacties
0