Hudzilla.org - the homepage of Paul Hudson
Contents > Functions > Playing with strings Wish List | Report Bug | About Me ]

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.





<< 4.7.1 Reading from part of a string: substr()   4.7.3 Converting to and from ASCII: chr() and ord() >>
Table of Contents
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!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
A PHP User - 07 Sep 2008

You're using single quotes instead of double quotes.

Try this:

<?php

print str_replace("\n", "<br>", "a\nb\nc");

?>

A PHP User - 07 Sep 2008

i have skipped a bit from 4.2, i just want to know how you replace the '\n' in the examples provided into '<br>'. I have read everything here and where i am stumbling is the third parameter. Instead of a varible i want to use the conditonal statement print.

Look:
<?php require "replace.php"; ?>
<?php
print date("H:i") . "\n";
print "The day yesterday was " . date("l", time() - 86400) . "\n";
print "The year is " . date("Y") . "\n";
print date("jS of F Y") . "\n";
print "My birthday is on a " . date("l", strtotime("22 Dec 2004")) . " this year.\n";
print date("\M\y b\i\\r\\t\h\d\a\y \i\s o\\n \a l \\t\h\i\s \ye\a\\r. ", strtotime("22 Dec 2004")) . "\n";
?>


The best I can come up with is:
<?php
$str = str_replace('\\n','<br>',print);
return $str;
?>
Which happens to do nothing by the way. Please Help :'(

A PHP User - 07 Sep 2008

xcellent

Unix Programmer - 07 Sep 2008

Just a nit - your sentence "Next up we have str_replace() which, unsurprisingly, replaces one parts of a string with new parts you specify." could stand some cleanup. Intstead of 'one parts', you meant 'one or more parts'.

Romack L. Natividad / romacknatividad@yahoo.com - 07 Sep 2008

// revised -- oops sori :)
function stripWhitespace($str){
// str_replace($searchStr, $replaceWithStr, $targetString)
$str = str_replace("\0", "", $str); // NUL 0
$str = str_replace(chr(0x09), "", $str); // \t 9
$str = str_replace(chr(0x0A), "", $str); // \n 10
$str = str_replace(chr(0x0B), "", $str); // vtab 11
$str = str_replace(chr(0x0D), "", $str); // \r 13
return $str;
}

Romack L. Natividad / romacknatividad@yahoo.com - 07 Sep 2008

//
// stripWhitespaces
//
// Removes unnecessary whitespace from the string
//
// params:
// $str - The string to clean up
//
// returns:
// clean string, free from whitespace
//
function stripWhitespace($str){
// str_replace($searchStr, $replaceWithStr, $targetString)
$str = str_replace("\0", "", $str); // NUL 0
$str = str_replace("\9", "", $str); // \t 9
$str = str_replace("\0A", "", $str); // \n 10
$str = str_replace("\0B", "", $str); // vtab 11
$str = str_replace("\0D", "", $str); // \r 13
return $str;
}

A PHP User - 07 Sep 2008

How to change it like:
monkeys -> giraffes
Monkeys -> Giraffes

Kyku <kyku at os dot pl> - 07 Sep 2008

I think it is useful to note that the $count parameter in str_replace is available from PHP 5.



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is nine plus two?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow