Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page