3

My string of numbers are not replacing correctly.

I am expecting the output after replacing to be 9876543210 but it doesnt seem to be the case.

What am i doing wrong?

<?php $numbers = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); $code = array('9', '8', '7', '6', '5', '4', '3', '2', '1', '0'); $pre = '0123456789'; echo $pre . " ==> " . str_replace($numbers, $code, $pre); ?> 
4
  • 1
    Why don't you use strrev() ? Commented Jul 10, 2013 at 9:25
  • what is your output instead? Commented Jul 10, 2013 at 9:25
  • @HamZa : that's just a simple example I am thinking of jumbling the code in another order. @STTLCU : my output is 0123443210 Commented Jul 10, 2013 at 9:29
  • 1
    The problem is in the fact that the replace goes in the array order, that meaning that from 0 to 4 (at the beginning), the chars are replaced twice. Take a look at this example @ php.net php.net/manual/en/function.str-replace.php#example-4820 Commented Jul 10, 2013 at 9:31

2 Answers 2

6

That produces the output 0123443210 because str_replace with an array will start replacing earlier matches as it iterates over $numbers

For a single letter transposition like this, use strtr instead

 $encoded = strtr($pre, "0123456789", "9876543210"); 
Sign up to request clarification or add additional context in comments.

1 Comment

Seems like a good looking replace. I think in this case this would be the more sensitive way of doing it.
1

It's a bit long to explain but let me show you what's happening. For each element in the array it's replacing everything from the start from the string. Let's define N for $number and C for $code and R for $result

N C R 0 9 9123456789 1 8 9823456789 2 7 9873456789 3 6 9876456789 4 5 9876556789 5 4 9876446789 6 3 9873443789 7 2 9823443289 8 1 9123443219 9 0 0123443210 

Thus you should use the solution provided by Paul using strtr()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.