How to replace text inside a string in PHP

- by

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:

$originalText = "Now is the time when xxxx should be replaced.";
$replacement = str_replace('xxxx', 'Something', $originalText);
echo $replacement;

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:

$originalText = "Now is the time when xxxx should be replaced with xxxx.";
$replacement = str_replace('xxxx', 'Something', $originalText);
echo $replacement;

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

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



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.