How to replace a string with a string in PHP

String replacements in PHP are very simple and as per usual, can be done in a
variety of different ways. First let’s take a look at the most simple form of
a string replacement:

str_replace('blue', 'red', 'My favorite color is blue'

The first argument is the string you want to replace, the second is the string
you want to replace it with and the last argument is the string you want to
do the replacement in/to. You can also pass a fourth argument that allows you
to limit the number of replacements that occur.

The str_replace() function also allows you to pass in arrays for the first
two arguments to do multiple replacements in a single pass. If the first
argument is an array but the second is a string, all strings found in the array
will be replaced with the second argument. If both arguments are arrays, the
text used to replace will come from the matching key in the second array:

str_replace(array('red', 'blue'), 'green', 'I like blue, red and green'

str_replace(
    array('red', 'blue'),
    array('green', 'yellow'),
    'I like blue red and green'

This is great for simple string replacements, but you may have noticed that
the replacement only works on exact matches. What if we wanted to replace
“blue”, “Blue” and every other case combination in between? That’s where
preg_replace() comes in. This function allows you to do a replacement based
on a regular expression and is quite powerful in comparison:

preg_replace('/blue/gi', 'red', 'blue Blue BLUE bLUe BluE'

Not to dive too deep into writing regular expressions, but the previous code
snippet says “hey, find the string ‘blue’, regardless of case, all of instances
and swap it out for the string ‘red’”. Granted, this doesn’t maintain the case
of the original string, I’ll leave that for another post 🙂

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.