正则表达式------命名子模式,做数组的键

在正则表达式的实际应用中,我们经常需要将匹配出的模式进行命名,以命名的键值对形式放在数组中,常见的应用如:MVC模式中的路由。

命名子模式的语法:(?P<name>pattern)     和     (?’name’pattern)   两种方式

如:

$num = "xiaoming 24";
preg_match("/(?P<name>\w+) (?P<age>\d+)$/",$num,$me);
print_r($me);
Array
(
[0] => xiaoming 24
[name] => xiaoming
[1] => xiaoming
[age] => 24
[2] => 24
)

 

在mvc路由的一个应用:
$str = "/user-account/view/123";
$res = preg_match("@^/(?P<pageff>([a-zA-Z_-]+?))/(?P<action>([a-zA-Z_-]+?))/(?P<id>([^/]+?))$@u",$str,$maches);
print_r($maches);

Array
(
[page] => user-account
[action] => view
[id] => 123
[controller] => default
)



 

posted @ 2017-08-02 11:40  newAdmin  阅读(636)  评论(0编辑  收藏  举报