search and replace whole string with replacement

2019-07-26 03:17发布

问题:

I have a string that I would like to replace with another one if a word within the string is found.

 $pattern = array("/jacket/i","/jeans/i"); 
 $replacement = array("jacket","jeans"); 
 $string = 'Red jackets'; 
 $replaced_string = preg_replace($pattern, $replacement, $string);

I know the above wont work but i need to be able to use an array of patterns and replacements.

I would like the $replacement_string to be just "jacket"

Can someone point me out to a solution for this?

Thanks

回答1:

Maybe if you tweaked your original code just a bit like this:

$patterns = array("/.*jacket.*/i", "/.*jeans.*/i");
$replacements = array("jacket", "jeans");
$string = 'Red jackets';
$replaced_string = preg_replace($patterns, $replacements, $string);

Putting those .* in there will clear out the rest of the string... and leave you with just the replacement string you want.



回答2:

You know the above won't work how?

Review the php dev guide: http://php.net/manual/en/function.preg-replace.php

I have quoted the noteworthy section:

pattern

The pattern to search for. It can be either a string or an array with strings.

replacement

The string or an array with strings to replace. If this parameter is a string and the pattern parameter is an array, all patterns will be replaced by that string. If both pattern and replacement parameters are arrays, each pattern will be replaced by the replacement counterpart. If there are fewer elements in the replacement array than in the pattern array, any extra patterns will be replaced by an empty string.

So what all that says basically is you can make you're pattern array be all the words you want to replace. Then you can just use the word "jacket" as your replacement and then anytime a word in your pattern array is found it will replace it with jacket.

Are you having problems getting this to work?



回答3:

How about this:

$pattern = array("/jacket/i","/jeans/i"); 
$replacement = array("jacket","jeans"); 
$string = 'Red jackets'; 

foreach ($pattern as $i => $p) {
    if (preg_match($p, $string)) {
        $replaced_string = $replacement[$i];
        break;
    }
}

echo $replaced_string;