Have you ever wanted to take a string and replace every occurance of a substring with something else? Regular Expression voodoo is what first comes to mind for a lot of PHP developers. But there is an easier way that just happens to be faster.
Str_Replace() accepts up to four parameters, three of which are required. The first is the substring to look for, the second is the substring to replace it with, and the third is the input string. (The optional fourth parameter is used to set a maximum amount or times to run the replace operation.) The function returns the new string.
You’re not limited to replacing a single substring either. You can pass arrays for the search and replace parameters.
How about a real-word example? Suppose you have a script that accepts user input, which is then stored to be later displayed on part of a website. (A guestbook or blog comments script, something like that.) Now, users can input basic HTML for formatting, but they always have a habit of using deprecated tags like <i> and <b>. Sure, it’s not a huge deal, but you prefer to have the more semantically-correct <em> and <strong>. So you use Str_Replace() to fix the submissions before they are stored, like this:
$input = "Hello, this is an <i>interesting</i> message left by a user called <b>Jane Doe</b>.";
$search = array("<i>", "</i>", "<b>", "</b>");
$replace = array("<em>", "</em>", "<strong>", "</strong>");
echo str_replace($search, $replace, $input);
This basic script will output “Hello, this is an <em>interesting</em> message left by a user called <strong>Jane Doe</strong>.”