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


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

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

如:

$num = "xiaoming 24";
preg_match("/(?P\w+) (?P\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([a-zA-Z_-]+?))/(?P([a-zA-Z_-]+?))/(?P([^/]+?))$@u",$str,$maches);
print_r($maches);

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