4.7.2 Replacing parts of a string: str_replace() and str_ireplace()This is NOT the latest copy of this book; click here for the latest version.
mixed str_replace ( mixed search, mixed replace, mixed source [, int &count])
mixed str_ireplace ( mixed search, mixed replace, mixed source [, int &count])
Next up we have str_replace() which, unsurprisingly, replaces one parts of a string with new parts you specify. Str_replace() 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, if passed, will be filled with the number of replacements made.
Str_replace() is a very easy way to find and replace text in a string. Here is how it works:
<?php
$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" - simple, really. Now consider this piece of code:
<?php
$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". The reason for this is because the first parameter to str_replace() is "Monkeys" rather than "monkeys", and PHP is case sensitive with strings!
There are two ways to fix the problem: either change the first letter of Monkeys to a lowercase M, or, if we're not sure which case we will find, we can switch to the case-insensitive version of str_replace(): str_ireplace().
<?php
$string = "An infinite number of monkeys";
$newstring = str_ireplace("Monkeys", "giraffes", $string);
print $newstring; ?>
This time around, we find that $newstring is now "An infinite number of giraffes", as hoped. The key is that PHP will now replace "Monkeys", "monkeys", "MONKEYS", etc.
When used, the fourth parameter is passed by reference, and PHP will set it to be the number of times your string was found and replaced. Take a look at this example:
<?php
$string = "He had had to have had it.";
$newstring = str_replace("had", "foo", $string, $count);
print "$count changes were made.\n"; ?>
That should output three, as PHP will replace "had" with "foo" three times.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|