Tag Archives: str_replace

How to replace text inside a string in PHP

If we have a string and would like to replace a portion of it, we can use the str_replace() function in PHP. It works like this:

str_replace (‘whatToReplace’, ‘theReplacement’, ‘originalText’);

It’s easy to remember… but I always get confused when I look this up in the manual. Here’s an example:

This works well if there’s only one occurrence that can be replaced. If you had ‘xxxx’ twice in the original text, both xxxx’s would be replaced by Something:

This function is cAsE SenSitiVe – you can also use str_ireplace() which will ignore case.

You can also do it with Regular Expressions (shudders):