Hommer Smith
Hommer Smith

Reputation: 27852

Preg replace with words from an array

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.

Upvotes: 2

Views: 2058

Answers (2)

Kathiravan
Kathiravan

Reputation: 699

$word              = array("test","test1");
$search_string     = "(".implode("|",$word).")";
$value             = preg_replace("/$search_string\s+\S+)/i","$1",$text);

Try this..

Upvotes: 2

Xiao Jia
Xiao Jia

Reputation: 4259

You can use indexed arrays with preg_replace().

<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[0] = 'slow';
$replacements[1] = 'black';
$replacements[2] = 'bear';
echo preg_replace($patterns, $replacements, $string);
?>

The above example will output:

The slow black bear jumped over the lazy dog.

Upvotes: 4

Related Questions