0

I am trying to replace every A-Z,a-z character to the 13th character from their index. The code above should output Aqeai4pyh_w.

echo 'j_ulc4vnrdN
';

$string = "j_ulc4vnrdN";

$arr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$arr2 = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm';

$l = array();
$arr1 = str_split($arr);
$arr22 = str_split($arr2);
print_r($arr1); 
print_r($arr22); 
foreach(str_split($string) as $k){
    echo $k.'
      ';
    $k = str_replace($arr1,$arr22,$k);



    echo $k.'
      ';
    $l[] = $k;
    //  print_r($l);
}

echo  strrev(implode('',$l));

But it outputs Adeai4clh_j Anyone has any idea how is this happening?

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
Avadhesh18
  • 27
  • 1
  • 9
  • Thank you, that works perfectly well. But I would also like to know why the code I have posted is behaving like that. – Avadhesh18 Mar 26 '20 at 08:25
  • `str_replace` works recursively and takes each array element one at a time. When you replace j with w you move on to then replace w with j again. Use [`strtr`](https://www.php.net/manual/en/function.strtr.php) to do a 1-1 replacement without recursing – apokryfos Mar 26 '20 at 08:27
  • It works from first to last in the needles, the only reason why 'N' works is that it translates it to 'A', but the 'A' needle has already been checked, so it doesn't replace it again. – Nigel Ren Mar 26 '20 at 08:29

0 Answers0