PHP Str_Replace() Function

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

There’s a lot that could be done with Str_Replace. You could write a BBCode implementation, censor words you would rather people didn’t use on your site, cut potentially malicious code (Flash, JavaScript, etc) from user submissions, etc. It’s a powerful tool, and one that any PHP developer should be aware of.

  • The Frosty

    Thanks for this one. Think you already helped out via Twitter. But still my <code>preg_replace </code> worked better. :)

    • redwall_hp

      That's okay, I'm sure someone else will find it useful. I use the function often enough.

      It actually executes faster than preg_replace, though it's not always the right tool for the job.