Better PHP String Replace with the strtr Function

The PHP strtr function is well suited in many cases to perform string replace routines instead of PHP's str_replace.

There are two signatures for the function, but the one we're interested in here is the following:

 strtr ( string $str , array $replace_pairs ) : string

If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

The main "nice-to-haves" are the facts that the search/replace is run from longest string to shortest, and the fact that once a substitution takes places, the substituted string will not be eligible for further matches / substitutions, which can be pain points when using the ubiquitous str_replace function.

Refer to the PHP documentation for the function for more info: https://php.net/strtr.

Tags

 PHP  PHP functions  quick tips  web development