Replacing parts of a string

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.

 

Next chapter: Converting to and from ASCII >>

Previous chapter: Reading from part of a string

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar