2

如果需要的模式存在,我需要用数组中的某个模式替换字符串:

$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;
}
4

1 回答 1

4

preg_replace接受模式和替换的数组参数。

preg_replace(array_keys($patters), array_values($patterns), $string);
于 2013-03-31T15:19:29.693 回答