手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆
浏览模式: 标准 | 列表Tag:perl

一个被忽略的正则功能

在setting sun的博客上发现一篇 文章,他认为:

PHP代码
  1. $p = "/^(?<ip>.*) (?<time>.*)$/";    
  2. $s = "10.4.0.111 2009-09-09";    
  3. preg_match($p$s$m);    
  4. print_r($m);    

输出:

XML/HTML代码
  1. Array ( [0] => 10.4.0.111 2009-09-09 [ip] => 10.4.0.111 [1] => 10.4.0.111 [time] => 2009-09-09 [2] => 2009-09-09 )   
这个数组中有ip,time的key,他认为这是PHP5.3的功能。回复中echo说没什么特别。

事实上,这个还真不是php5.3的功能,它是PHP4.3开始就有的功能。详情可以看手册:

Pattern Syntax -- Describes PCRE regex syntax这一章。其中有一段就是:
XML/HTML代码
  1. It is possible to name the subpattern with (?P<name>pattern) since PHP 4.3.3. Array with matches will contain the match indexed by the string alongside the match indexed by a number, then.   
所以,这还真不是啥新功能,只是我们很少用到而已。顺便说一句,今天的lamp分享中,祁宏还真的提到了这一点(关于分享内容我写了博客,但祁宏讲的内容,我没有详细记录参加lamp聚会有感 ),所以我才特别有印象。
本想回复到setting sun的博客上的,但。。。后来打不开了,原文网址为:http://www.setting.cc/blog/archives/2.html

 

 

Tags: perl, preg_match, php, pattern