Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP str_replace numbers with other numbers

Tags:

string

php

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);
?>
like image 939
chongzixin Avatar asked Sep 15 '26 05:09

chongzixin


2 Answers

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");
like image 82
Paul Dixon Avatar answered Sep 16 '26 19:09

Paul Dixon


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()

like image 22
HamZa Avatar answered Sep 16 '26 19:09

HamZa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!