Understanding how str_replace and strtr work in php

$search = array('A', 'B', 'C', 'D', 'E'); $replace = array('B', 'C', 'D', 'E', 'F'); $subject = 'A'; $trans = array('A' => 'B','B'=>'C','C'=>'D','D'=>'E','E'=>'F'); echo str_replace($search, $replace, $subject); echo "<br/>"; echo strtr($subject,$trans); Output: F B 

When using str_replace, I get F, using strtr I get B

While I get this, for str_replace: it replaces from left to right, so A is replaced by B without marking, the position has already been replaced, therefore it again finds B, which is replaced by C, and so on, to get the value F.

For strtr: I replace A with B and remember that it was replaced at this position,

Did I understand correctly? can someone explain to me?

+4
source share
1 answer

Yes this is correct. str_replace() performs its replacements sequentially, while strtr() works through each character in a string and replaces it only once.

0
source

All Articles