Example #2 preg_replace()中使用基于索引的数组 <?php $string = 'The quick brown fox jumped over the lazy dog.'; $patterns = array(); $patterns[0] = '/quick/'; $patterns[1] = '/brown/'; $patterns[2] = '/fox/'; $replacements = array(); $replacements[2] = 'bear'; $replacements[1] = 'black'; $replacements[0] = 'slow'; echo preg_replace($patterns, $replacements, $string); ?> 以上例程会输出: The bear black slow jumped over the lazy dog.
对模式和替换内容按key进行排序我们可以得到期望的结果。 <?php ksort($patterns); ksort($replacements); echo preg_replace($patterns, $replacements, $string); ?> 以上例程会输出: The slow black bear jumped over the lazy dog.