我认为我不能在一个 swell foop 中做到这一点,但我不是要求: - )
我当然可以定义一对一$pattern
和$replacement
数组,我可以重复定义$pattern
数组和$replacement
数组,但是我可以同时执行一次?
假设我有三组,如:
$p1 = array('sis','boom','bah');
$r1 = 'cheers';
$p2 = array('boo','hiss');
$r2 = 'jeers';
$p3 = array('guinness','heineken','budweiser');
$r3 = 'beers';
我想用一个大的干草堆替换所有模式的实例和它们各自的单个替换。我可以定义一个preg_replace
调用来实现此目的吗?
答案 0 :(得分:1)
我认为你需要将单词边界与基于正则表达式的函数结合起来。
考虑这个strtr()
演示:
$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);
输出:
Rah rah, cheers cheers cheers, I read a jeersk on beers
// ^^^^^ Oops
您只需要使用管道内爆needle
元素并将它们包装在非捕获组中,以便将单词边界应用于所有子字符串,如下所示:
代码:(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);
输出:
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
*注:
单词边界\b
确保整个单词匹配,避免意外的不匹配。
如果您需要不区分大小写,请在每个正则表达式模式的末尾使用i
标志。例如/\b(?:sis|boom|bah)\b/i
答案 1 :(得分:0)
$subject = 'sis + boo + guinness';
echo preg_replace(['/sis|boom|bah/','/boo|hiss/','/guinness|heineken|budweiser/'],['cheers','jeers','beers'],$subject);
// the result would be cheers + jeers + beers
替换 要替换的字符串或数组。如果此参数是a string和pattern参数是一个数组,所有模式都是 替换为该字符串。如果是模式和替换参数 是数组,每个模式将被替换替换 对方。如果替换数组中的元素少于 在模式数组中,任何额外的模式都将被替换为空 串。 ...
如果subject是一个数组,则执行搜索和替换 主题的每个条目,返回值也是一个数组。