preg_replace()的每个参数(除了limit)都可以是一个数组。如果pattern 和replacement
都是数组,将以其键名在数组中出现的顺序来进行处理,不一定和索引的数字顺序相同。如
果使用索引来标识哪个pattern 将被哪个replacement 来替换,应该在调用preg_replace()之前
用ksort()对数组进行排序。
134 PHP 网络编程技术与实例
实例 3-36 数组替换
本实例演示利用preg_replace 函数进行数组替换,如代码3-36 所示。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
  <head>
   <title> preg_replace_1.php </title>
   <meta charset="UTF-8">
   <meta name="Author" content="">
   <meta name="Keywords" content="">
   <meta name="Description" content="">
  </head> <body>
<?php
 $string = "The quick brown fox jumped over the lazy dog.";
 $patterns[0] = "/quick/";
 $patterns[1] = "/brown/";
 $patterns[2] = "/fox/";
 $replacements[2] = "bear";
 $replacements[1] = "black";
 $replacements[0] = "slow";
 print preg_replace($patterns, $replacements, $string);
 echo "<br>";
 //对字符串进行键值排序
 ksort($patterns);
 ksort($replacements);
 print preg_replace($patterns, $replacements, $string);
 ?>
  </body>
 </html>


The bear black slow jumped over the lazy dog.
The slow black bear jumped over the lazy dog. 

如果subject 是数组,则会对subject 中的每个项目执行搜索和替换,并返回一个数组。
如果 pattern 和replacement 都是数组,则preg_replace()会依次从中分别取出值来对subject
进行搜索和替换。如果replacement 中的值比pattern 中的少,则用空字符串作为余下的替换
值。如果pattern 是数组而replacement 是字符串,则对pattern 中的每个值都用此字符串作为
替换值。反过来则没有意义了。
/e 修正符使preg_replace()将replacement 参数当作PHP 代码(在适当的逆向引用替换完
之后)。
提示
要确保 replacement 构成一个合法的PHP 代码字符串,否则会在包含
preg_replace()的行中出现语法解析错误。