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[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 标记变成大写。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值