PHP String Replace Functions – Cheatsheet and Tutorial


PHP is famous for the simple and rich string modification methods. One important type of modification is to replace a string with another. Here are the possible methods, how to use it. At the end you will find a performance comparison over all the function and different input sizes.

Simple str_replace

str_replace('search string aka needle', 'replace with', 'in this string aka haystack');

Basic Example

$name = 'bill';
$replaceName = 'steve';
$string = 'bill is a genius.';

$newString = str_replace($name, $replaceName, $string); // => steve is a genius.

Get Replacement Count

// ... via pass-by-reference variable
str_replace('one','two','one one one', $count);
echo $count; // = 3

Use Arrays as $search and $replace

$search = array('a','b');
$replace = array('b','a');
echo str_replace($search, $replace, 'ababab'); // => aaaaaa

Insensitive str_replace Function

// str_replace is case-sensitive ... str_ireplace not
echo str_ireplace('A', 'b', 'aA'); // => bb

Use Strings like Arrays

$str = 'a string';
$str[0] = 'A'; // change first char
$str[strlen($str)] = '!'; // append a char

Use substr_replace for Replacing Strings by Index

$str = 'another string';

// insert a string on position 8 (overwrite 0 chars)
$str = substr_replace($str, 'nice ', 8, 0);

// overwrite 5 chars on pos 8 with the new string
$str = substr_replace($str, 'not nice ', 8, 5);

strtr Single Byte Replacements

echo strtr('this is a nice text', "t", "T"); // => This is a nice TexT

// a bit strange but ... replaces char by char ... all x=>X, t=>T, e=>E
echo strtr('this is a nice text', "xte", "XTE"); // => This is a nicE TEXT

// use it with associative arrays
echo strtr('this is a nice text', array("xt"=>"XT")); // this is a nice teXT

Swiss Army Knife preg_replace

echo preg_replace("/nice/", "very nice", "this is a nice text");

// replace with limit
echo preg_replace("/t/", "T", "this is a nice text", 1);

// replace with no limit
echo preg_replace("/t/", "T", "this is a nice text", -1);

// replace with $count variable
echo preg_replace("/t/", "T", "this is a nice text", -1, $count);

// replace with arrays, returns array("bbbbbb","bbbbbbb")
var_dump( preg_replace(array('/a/'), array('b'), array('ababab','bababa')) );

It’s getting complicated now … preg_replace_callback

// replace with callback, returns a with uppercase A
preg_replace_callback('/a/', function($match){
    return strtoupper($match[0]);
}, 'ababab');

// use create_function if you want a slow version (see below)
preg_replace_callback('/a/', create_function(
    '$matches',
    'return $matches[0];'),
'ababab');

“ereg_replace” is marked as deprecated and should not used anymore.

Here is the performance overview over the different replace functions with different parameters, avoid strtr with assoc array and preg_replace_callback with create_function it’s really slow.

How will the performance change if the data-size changes? Size matters but the count of replacements matters much more, many matches makes str_replace slow.

Here is the code template for the str_replace performance tests. microtime_float comes from php.net help pages.

$s = 'ababababab';
$a = 'cdcdcdcdcd';
$b = 'b';

$start = microtime_float();
for($i=0; $i<100000; $i++) {
    str_replace($a, $b, $s, $c);
}
echo "input 10b, search 10b, $c\t".round(microtime_float()-$start, 4)."\n";

Do you know more or better methods to replace strings ... share it in comments!