如果需要的模式存在,我需要用数组中的某个模式替换字符串:
$patterns = [
'PATTERN#1' => 'REPLACE#1',
'PATTERN#2' => 'REPLACE#2',
];
$string = 'SOME STRING TO PREG_REPLACE';
哪种方式会更快:
// PREG_REPLACE ONLY FOR MATCHED PATTERN:
foreach ($patterns as $pattern => $replace) {
if (preg_match($string, $pattern)) {
preg_replace($pattern, $replace, $string);
break;
}
}
或者
// PREG_REPLACE FOR ALL PATTERNS:
foreach ($patterns as $pattern => $replace) {
preg_replace($pattern, $replace, $string);
break;
}