The str_replace function in PHP, is similar to the find and replace function that you’ll find in most text editors. Microsoft Word, Google Docs, Notepad, WordPad, Gedit, and a gaggle of other text editors, all have the find and replace function. It’s a very neat feature that comes in very handy when doing wholesale changes to a document.
In PHP, I use the str_replace function mostly to filter unwanted characters, like commas, quotes, etc from a certain string. The string can originate from a form or database. It doesn’t really matter. In this example, I have a string called $a. I will use the str_replace function to search for a word ‘foo’ and replace it with the word ‘bar.’
Replace Foo With Bar
$a = 'foo, is a great word.'; $b = str_replace('foo', 'bar', $a); echo $b;
The result: ‘bar, is a great word.’
$a = 'foo, is a great word.'; echo $b = str_replace(',', ' ', $a);
The result: ‘foo is a great word.’
Notice I used a shortcut to echo the string $b, while assigning to it the str_replace function. You can use str_replace to filter and replace a character, a word or a group of words from within a string.