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:

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





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.