thinkphp路由的完整匹配

完整匹配

完整匹配

如果希望仅仅匹配

http://tp5.com/hello/thinkphp

而不能访问这种地址

http://tp5.com/hello/thinkphp/city/shanghai

就可以使用完整匹配功能,路由定义规则改为:

Route::get(hello/:name$,index/index/hello);

路由规则最后用$结尾就表示该路由规则是完整匹配的。 (有部分情况下注册的路由规则是自动完整匹配的,比如说资源路由,我们后面会讲到。)

或者使用路由参数

Route::get(hello/:name,index/index/hello,[complete_match=>true]);

两种方式的作用是相同的(实际上使用$结尾的路由定义最终也会解析成complete_match参数的方式)。

【5.1须知】 可以使用下面的方法定义局部完整匹配
Route::get(hello/:name,index/index/hello)->completeMatch();

如果需要全局的路由规则定义都是完整匹配的话,可以直接修改应用的配置参数:

route_complete_match	=>	true

当开启全局完整匹配后,个别路由规则也支持单独关闭完整匹配,使用下面的方式即可:

Route::get(hello/:name,index/index/hello,[complete_match=>false]);

变量规则

默认情况下,路由变量会匹配所有的字符,但很多时候,我们需要约束变量的规则进行路由匹配:

Route::get(hello/:name/[:city],index/index/hello,[],[ name => [A-Za-z0-9]+ , city => [A-Za-z]+ ]);

分别对name和city变量定义了变量规则(采用正则表达式)。

【5.1须知】 可以使用下面的方法定义变量规则
Route::get(hello/:name/[:city],index/index/hello)
->pattern([name=> [A-Za-z0-9]+ , city => [A-Za-z]+ ]);

或者多次调用

Route::get(hello/:name/[:city],index/index/hello)
->pattern(name,[A-Za-z0-9]+)
->pattern(city,[A-Za-z]+);

下面的URL地址会正确匹配

http://tp5.com/hello/thinkphp2015
http://tp5.com/hello/2015/beijing

下面的URL地址则无效

http://tp5.com/hello/think_php
http://tp5.com/hello/thinkphp/2015
经验分享 程序员 微信小程序 职场和发展