PHP comes with powerful built-in functions for manipulating and handling strings. So if you need to replace multiple characters in a string at once, PHP has got you covered. In this article, I’ll show two functions to tackle this problem.
Approach 1: the str_replace() function
This function is used to replace all occurrences of the “needle” string in a “haystack” string with a replacement string.
/** code example */
$haystack = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
$needle = ['a', 'm', 'o'];
$replace_with = '?';
$new_string = str_replace($needle, $replace_with, $haystack);
echo $new_string; # L?re? ipsu? d?l?r sit ??et, c?nsectetur ?dipiscing elit, sed d? eius??d te?p?r incididunt ut l?b?re et d?l?re ??gn? ?liqu?.
Approach 2: the preg_replace() function
The preg_replace() function is also used to replace multiple characters in a string. The only difference is that it performs a regular expression search and replace.
/** code example */
$haystack = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
$needle = '%[amo]%'; # a regex
$replace_with = '?';
$new_string = preg_replace($needle, $replace_with, $haystack);
echo $new_string; # L?re? ipsu? d?l?r sit ??et, c?nsectetur ?dipiscing elit, sed d? eius??d te?p?r incididunt ut l?b?re et d?l?re ??gn? ?liqu?.
That’s all. I hope you find this post helpful.