`
lhx1026
  • 浏览: 300664 次
  • 性别: Icon_minigender_2
  • 来自: 广州
社区版块
存档分类
最新评论

PHP preg_replace的使用

    博客分类:
  • php
阅读更多

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[0] = "/quick/";
$patterns[1] = "/brown/";
$patterns[2] = "/fox/";

$replacements[2] = "bear";
$replacements[1] = "black";
$replacements[0] = "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 楼 joenali 2011-03-30  
$string = "April 15, 2003"; 
$pattern = "/(/w+) (/d+), (/d+)/i"; 
$replacement = "/${1}1,/$3"; 
print preg_replace($pattern, $replacement, $string); 
写错了,应改为
$string = "April 15, 2003"; 
$pattern = "/(\w+) (\d+), (\d+)/i"; 
$replacement = "\${1}1,\$3"; 
print preg_replace($pattern, $replacement, $string); 
真搞不懂你有没有测试

相关推荐

Global site tag (gtag.js) - Google Analytics