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):

About Jay Versluis

Jay is a medical miracle known as a Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

Add your voice!