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.

  • http://php.net/manual/en/function.str-replace.php
  • http://www.php.net/manual/en/function.str-ireplace.php

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

  • http://stackoverflow.com/questions/3426265/php-string-replace-match-whole-word

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.

Add your voice!