Tip: str_replace()

Here’s a quick little tip for using PHP’s str_replace() with many values. Sometimes it’s fine to just do this:

$string = str_replace( 'to_replace', 'replacement_string', $string );
$string = str_replace( 'to_replace', 'replacement_string', $string );
$string = str_replace( 'to_replace', 'replacement_string', $string );

That method is fine but can get messy with many replacements. Another method is to create two arrays, one being a set of values to search for and another for the replacement values.

$search = array( 'one', 'two', 'three' );
$replace = array( '1', '2', '3' );
$string = str_replace( $search, $replace, $string );

The method I prefer to use is a single array and utilizing PHP’s array_keys() and array_values() functions.

$replace = array( '{username}' => 'jrtashjian', '{twitter}' => '@jrtashjian', '{email}' => 'jrtashjian@gmail.com' ); $string = str_replace( array_keys($replace), array_values($replace), $string);

The method I prefer to use is a single array and utilizing PHP’s array_keys() function.

$replace = array(
    '{username}' => 'jrtashjian',
    '{twitter}' => '@jrtashjian',
    '{email}' => 'jrtashjian@gmail.com'
);
$string = str_replace( array_keys( $replace ), $replace, $string );

Hope this quick tip helped you out.

EDIT:
Brendon Kozlowski called out that you wouldn’t need to invoke the array_values() function, you could just pass the variable itself as the parameter. Surprised I didn’t catch that!

One thought on “Tip: str_replace()”

Comments are closed.