Home >Backend Development >PHP Tutorial >Performance comparison of php strtr function and str_replace_PHP tutorial
PHP’s strtr function has higher performance than str_replace function and can be used instead of str_replace. strtr has two forms:
string strtr ( string $str , string $from , string $to )
string strtr ( string $str , array $replace_pairs )
When using the first method, the string lengths of the parameters $from and $to must be the same, otherwise the extra characters (whether there are more $from or more $to) will be ignored.
For example $str = 'a-=b' ;
When $from='-=', $to='CD', output 'aCDb', because '-=' and 'CD' have the same length, there is no problem.
When $from='-=', $to='CDE', 'aCDb' is output, and the 'E' in $to is ignored.
When $from='-=', $to='C', 'aC=b' is output, and the '=' in $from is ignored.
When using the second form, there is no such problem, and redundant notes will not be ignored.
Therefore, if you deliberately use the strtr function instead of str_replace, and use the first form, you must pay attention to this feature, which may be a trap.