I have an array of words that have to be replaced from a string, let’s call it $my_replacements. I also have a string, let’s call it $my_string, that can contain some of those values in.
Right now I have this:
foreach ($my_replacements as $replacement) {
$replaced_value = preg_replace("/(^|[\n\r\f\t \.\,])" . $replacement . "([\n\r\f\t \.\,]|$)/iu", '', $my_string);
if($replaced_value !== $my_string) {
break;
}
}
And this was good if at the first replacement I wanted to exit the foreach. However, if the strings contains one or more of those values to be replaced it won’t work. How can I use preg_replace to find those words, and replace them all? And it’s important that I know if any replacements have been done.
You can use indexed arrays with
preg_replace().The above example will output: