zhangbinmy 发表于 2017-3-26 12:25:35

PHP preg_replace的使用

  preg_replace -- 执行正则表达式的搜索和替换

说明
  mixed preg_replace
( mixed pattern,
mixed replacement, mixed subject [, int limit])
  例子1:逆向引用后面紧接着数字的用法


$string = "April 15, 2003";
$pattern = "/(/w+) (/d+), (/d+)/i";
$replacement = "/${1}1,/$3";
print preg_replace($pattern, $replacement, $string);
/* Output
======
April1,2003
*/
  
如果搜索到匹配项,则会返回被替换后的   subject

,否则
返回原来不变的   subject


  
preg_replace()
的每个参数(除了   limit

)都可以是一个数组。如果   pattern

和   replacement

都是数组,将以其键名在数组中出现的顺序来进行处理。这不一定
和索引的数字顺序相同。如果使用索引来
标识哪个   pattern

将被哪个   replacement

来替换,应该在调用   preg_replace()
之前用   ksort()
对数组进行排序。   
  例子 2. 在 preg_replace()
中使用索引数组


$string = "The quick brown fox jumped over the lazy dog.";
$patterns = "/quick/";
$patterns = "/brown/";
$patterns = "/fox/";
$replacements = "bear";
$replacements = "black";
$replacements = "slow";
print preg_replace($patterns, $replacements, $string);
/* Output
======
The bear black slow jumped over the lazy dog.
*/
/* By ksorting patterns and replacements,
we should get what we wanted. */
ksort($patterns);
ksort($replacements);
print preg_replace($patterns, $replacements, $string);
/* Output
======
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 代码字符串,否则   PHP 会在报告在包含   preg_replace()
的行中出现语法解析错误。
  例子 3. 替换数个值


$patterns = array ("/(19|20)(/d{2})-(/d{1,2})-(/d{1,2})/",
"/^/s*{(/w+)}/s*=/");
$replace = array ("//3///4///1//2", "$//1 =");
print preg_replace ($patterns, $replace, "{startDate} = 1999-5-27");
  本例将输出:      

$startDate = 5/27/1999
  例子 4. 使用 /e 修正符


preg_replace ("/(<//?)(/w+)([^>]*>)/e",
"'//1'.strtoupper('//2').'//3'",
$html_body);
  这将使输入字符串中的所有 HTML 标记变成大写。
页: [1]
查看完整版本: PHP preg_replace的使用