Replace Multiple Strings in the Same Time

PHPPosted on

We all know the good old str_replace function. However, it offers a nice feature that is not so well known. With this native function, we can replace multiple substrings with multiple replacers.

The nice thing is, we can combine these functionalities. For example, we can replace a set of substrings to one specific replacer, or we can what substring should be replaced with what replacer.

Of course, we can also do this with the help of preg_replace, but in some cases, this simpler solution is handier.
// Basic usage
str_replace('?', '.', 'Hi! Are you ok?')

// Replace ? and ! to .
str_replace(['?', '!'], '.', 'Hi! Are you ok?');

// Replace ? to . and ! to ;
str_replace(['?', '!'], ['.', ';'], 'Hi! Are you ok?');

Need a web developer? Maybe we can help, get in touch!

Similar Posts

More content in PHP category