Jump to content

Trouble With Str_replace Using Arrays


astralaaron

Recommended Posts

Hi I am just messing around with this and ran into some trouble I can't figure out..

<?php$letters = array('.','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',' ');$numbers = array(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27);$num1 = 1;$num2 = 2;$num3 = 11;$num4 = 12;echo str_replace($numbers,$letters,$num1); // outputs: aecho str_replace($numbers,$letters,$num2); // outputs: becho str_replace($numbers,$letters,$num3); // outputs: aa	-instead of jecho str_replace($numbers,$letters,$num4); // outputs: ab	-instead of k?>

anything above 9 runs it twice on the single digit numbers? Does anyone have an explanation?

Link to comment
Share on other sites

It starts at the beginning of your numbers array. So it looks for "0" and replaces all the 0's it finds. Then it looks for "1" and replaces all the 1's it finds, etc...So the string "11" will be replaced by "aa" so by the time it gets to the number 11 there are no instances of "11" left in your string.Reversing the order of your arrays might help, but like DD said mixing numbers and strings isn't good and can be unpredictable.

Link to comment
Share on other sites

It starts at the beginning of your numbers array. So it looks for "0" and replaces all the 0's it finds. Then it looks for "1" and replaces all the 1's it finds, etc...So the string "11" will be replaced by "aa" so by the time it gets to the number 11 there are no instances of "11" left in your string.Reversing the order of your arrays might help, but like DD said mixing numbers and strings isn't good and can be unpredictable.
i tried putting the numbers into strings themselves with the same result
Link to comment
Share on other sites

The rest of jkloth's response is your explanation. The routine searches for ALL the 1's and then ALL the 2's, so by the time it gets to 11 and 12, those characters have been replaced already.In this instance, something like this works:$letters = array_reverse($letters);$numbers = array_reverse($numbers);also as jkloth suggested. I'm not sure what the long-term goal of this experiment is. Other solutions may be possible. Perhaps a regex.

Link to comment
Share on other sites

Archived

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

×
×
  • Create New...