PHP str_replace() Function

Usage — The PHP str_replace() function is used to replace one string with another in a case-sensitive manner .

It has the following syntax:

PHP

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

Here is an example of using str_replace():

PHP

// Output — Hello laura!
echo str_replace("LaUrA","Amanda","Hello laura!");

// Output — Hello Amanda!
echo str_replace("laura","Amanda","Hello laura!");

Return Value — If the string to be searched is an array, this function returns an array. Also, search and replace in this case is performed with every array element. If both search and replace are arrays, and replace has fewer elements than search, an empty string will be used for rest of the replacement values. If search is an array and replace is a string, the replace string will be used for every search value.

Additional Information — As I mentioned earlier, this function is case-sensitive. You should use the str_ireplace() function to perform a case-insensitive search. Also keep in mind that this function is binary-safe.

If you don’t need fancy replacing rules, you should generally use this function instead of preg_replace.

PHP Version and Changelog — The str_replace() function is available in PHP 4, PHP 5, PHP 7. The count parameter was added in PHP 5.0.

Relevant Functions — Other related PHP functions that you should know about are: str_ireplace() which replaces all occurrences of the search string with the replacement string in a case-insensitive manner, preg_replace which performs a regular expression search and replace and strtr() which translates characters or replace substrings.

Go Directly To — usage, parameters, working examples or additional tips.

Parameters

The search parameter is used to specify the value which we need to find, otherwise known as the needle. You can also use an array to specify multiple needles. This is a required parameter.

replace

The replace parameter is used to specify the replacement value that replaces found search values. You can also use an array to specify multiple replacements. This is a required parameter.

subject

The subject parameter is used to specify the string or array which is being searched and replaced on. This string is otherwise known as the haystack. This is also a required parameter.

If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

count

The count parameter is used to specify the number of replacements that should be performed. This is an optional parameter.

Working Examples

Here are some examples of using the str_replace() function:

Basic str_replace() examples

PHP

$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
// Output — Hll Wrld f PHP
echo str_replace($vowels, "", "Hello World of PHP");

$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");
// Output — You should eat pizza, beer, and ice cream every day.
echo str_replace($healthy, $yummy, $phrase);

str_replace("ll", "", "good golly miss molly!", $count);
// Output — 2
echo $count;

Examples of potential str_replace() gotchas

PHP

// Order of replacement
$str     = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order   = array("\r\n", "\n", "\r");
$replace = '<br />';

// Processes \r\n's first so they aren't converted twice.
$newstr = str_replace($order, $replace, $str);

// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
// Output — F
echo str_replace($search, $replace, $subject);

// For the same reason mentioned above
$letters = array('a', 'p');
$fruit   = array('apple', 'pear');
$text    = 'a p';
$output  = str_replace($letters, $fruit, $text);

// Output — apearpearle pear
echo $output;

Additional Tips

Here are some of the most upvoted tips taken from the comment section of the PHP manual:

  1. A faster way to replace the strings in multidimensional array is to json_encode it, do the str_replace() and then json_decode it, like this:

    PHP

    function str_replace_json($search, $replace, $subject){
         return json_decode(str_replace($search, $replace,  json_encode($subject)));
    }
    

    This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping method, and 10x simpler in coding.

    Compared to:

    PHP

    function str_replace_deep($search, $replace, $subject) {
        if (is_array($subject)) {
            foreach($subject as &$oneSubject)
                $oneSubject = str_replace_deep($search, $replace, $oneSubject);
            unset($oneSubject);
            return $subject;
        } else {
             return str_replace($search, $replace, $subject);
        }
    }
    

    Suggested by - nikolaz dot tang at hotmail dot com

  2. Feel free to optimize this using the while/for or anything else, but this is a bit of code that allows you to replace strings found in an associative array.

    For example:

    PHP

    $replace = array(
    'dog' => 'cat',
    'apple' => 'orange'
    'chevy' => 'ford'
    );
    $string = 'I like to eat an apple with my dog in my chevy';
    
    // Output — I like to eat an orange with my cat in my ford
    echo str_replace_assoc($replace,$string);
    

    Here is the function:

    PHP

    function strReplaceAssoc(array $replace, $subject) {
        return str_replace(array_keys($replace), array_values($replace), $subject);
    }
    

    Suggested by - Wes Foster

  3. Note that this does not replace strings that become part of replacement strings. This may be a problem when you want to remove multiple instances of the same repetative pattern, several times in a row.

    If you want to remove all dashes but one from the string ‘-aaa—-b-c—–d–e—f’ resulting in ‘-aaa-b-c-d-e-f’, you cannot use str_replace. Instead, use preg_replace:

    PHP

    $challenge = '-aaa----b-c-----d--e---f';
    
    // Output — -aaa--b-c---d-e--f
    echo str_replace('--', '-', $challenge);
    
    // Output — -aaa-b-c-d-e-f
    echo preg_replace('/--+/', '-', $challenge);
    

    Suggested by - moostende at gmail dot com

Further Reading

  1. You can read more about the PHP str_replace() function on PHP.net.

Reader Comments

1. You can register or login to post a comment. Asking readers to register improves the quality of discussion.

2. As a registered user, you will also get to access features like choosing between a light and dark theme or anything else that we might implement in future.

Follow Us For Updates

FacebookTwitterGoogle+
Go To Top