How to replace a string with a string in PHP

Josh Sherman
2 min read
Software Development 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 :)

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Born again Linux user. Founder of Holiday API, Backend Engineering Manager and Emoji Specialist at Mailshake (WE'RE HIRING!), and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Pears and Perils
Antifragile: Things That Gain from Disorder
Code Girls: The Untold Story of the American Women Code Breakers of World War II

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles