I think you will need to incorporate word boundaries with a regex-based function.
Consider this strtr() demo:
$string="Rah rah, sis boom bah, I read a book on budweiser";
$p1 = array('sis','boom','bah');
$r1 = 'cheers';
$p2 = array('boo','hiss');
$r2 = 'jeers' ;
$p3 = array('guinness','heineken','budweiser');
$r3 = 'beers';
$replacements=array_merge(
array_combine($p1,array_fill(0,sizeof($p1),$r1)),
array_combine($p2,array_fill(0,sizeof($p2),$r2)),
array_combine($p3,array_fill(0,sizeof($p3),$r3))
);
echo strtr($string,$replacements);
Output:
Rah rah, cheers cheers cheers, I read a jeersk on beers
// ^^^^^ Oops
You will just need to implode your needle elements using pipes and wrap them in a non-capturing group so that the word boundaries apply to all substrings, like this:
Code: (Demo)
$string="Rah rah, sis boom bah, I read a book on budweiser";
$p1 = ['sis','boom','bah'];
$r1 = 'cheers';
$p2 = ['boo','hiss'];
$r2 = 'jeers' ;
$p3 = ['guinness','heineken','budweiser'];
$r3 = 'beers';
$find=['/\b(?:'.implode('|',$p1).')\b/','/\b(?:'.implode('|',$p2).')\b/','/\b(?:'.implode('|',$p3).')\b/'];
$swap=[$r1,$r2,$r3];
var_export($find);
echo "\n";
var_export($swap);
echo "\n";
echo preg_replace($find,$swap,$string);
Output:
array (
0 => '/\\b(?:sis|boom|bah)\\b/', // unescaped: /\b(?:sis|boom|bah)\b/
1 => '/\\b(?:boo|hiss)\\b/', // unescaped: /\b(?:boo|hiss)\b/
2 => '/\\b(?:guinness|heineken|budweiser)\\b/', // unescaped: /\b(?:guinness|heineken|budweiser)\b/
)
array (
0 => 'cheers',
1 => 'jeers',
2 => 'beers',
)
Rah rah, cheers cheers cheers, I read a book on beers
*Notes:
The word boundaries \b ensure that whole words are match, avoiding unintended mismatches.
If you need case-insensitivity, just use the i flag at the end of each regex pattern. e.g. /\b(?:sis|boom|bah)\b/i
(sis|boom|bah)in your pattern if you're using regular expressions, otherwise str_replace can take an array of values for the search and replace with a single value.str_replace()will not respect word boundaries and may return unexpected results when a substring is found inside another substring.$string='My sister paid 500 baht for a boomerang';and useecho preg_replace('/sis|boom|bah/','cheers',$string);then you will get this mangled mess:My cheerster paid 500 cheerst for a cheerserangwhile there were no intended replacements to make.