Name

str_replace()

Synopsis

    mixed str_replace ( mixed needle, mixed replace, mixed haystack [, int
    &count] )

The str_replace() function replaces parts of a string with new parts you specify and takes a minimum of three parameters: what to look for, what to replace it with, and the string to work with. It also has an optional fourth parameter, which will be filled with the number of replacements made, if you provide it. Here are examples:

    $string = "An infinite number of monkeys";
    $newstring = str_replace("monkeys", "giraffes", $string);
    print $newstring;

With that code, $newstring will be printed out as "An infinite number of giraffes". Now consider this piece of code:

    $string = "An infinite number of monkeys";
    $newstring = str_replace("Monkeys", "giraffes", $string);
    print $newstring;

This time, $newstring will not be "An infinite number of giraffes", as you might have expected. Instead, it will remain "An infinite number of monkeys", because the first parameter to str_replace() is Monkeys rather than "monkeys", and the function is case- sensitive.

There are two ways to fix the problem: either change the first letter of "Monkeys" to a lowercase M, or, if you're not sure which case you will find, you can switch to the case-insensitive version of str_replace(): str_ireplace().

    $string = "An infinite number of monkeys";
    $newstring = str_ireplace("Monkeys", "giraffes", $string);
    print $newstring;

When used, the fourth parameter is passed by reference, and PHP will set it to be the number ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.