复制代码 代码如下:
<?php
//thinkphp 路由定义规则
$route = array(
'news/:action/:year/d/:month/:day'=>'news/read?year=:2&month=:3&day=:4',
'news/:action^delete|update|insert/:year/d/:month/:day'=>array( 'news/read?extra=:2&status=1','year=:2&month=:3&day=:4'),
);
$url = 'http://www.test.com/index.php/news/read/2012/2/21/extraparam/test.html';
//后缀名
$extension = 'html';
//可知: $_SERVER['PATH_INFO'] = 'news/read/2012/2/21/extraparam/test.html';
$regx = 'news/read/2012/2/21/extraparam/test.html';
//循环匹配路由规则
foreach($route as $key=>$value){
//如果匹配成功,则不继续匹配
if(parseUrlRule($key,$value,$regx,$extension))
break;
}
//运行结果: 打印$_GET
//Array
// (
// [actionName] => read
// [moduleName] => news
// [extra] => 2012
// [status] => 1
// [extraparam] => test
// [year] => 2012
// [month] => 2
// [day] => 21
// [finalUrl] => news/read?extra=2012&status=1&extraparam=test&year=2012&month=2&day=21
// )
// [Finished in 0.6s]
//相当于访问: http://www.test.com/news/read?extra=2012&status=1&extraparam=test&year=2012&month=2&day=21
//在部署时会把index.php隐藏,开启apache的重写模块
//重写规则 : RewriteRule ^(.+)$ /index.php/$1
//开启后,apache会自动把 http:/www.test.com/news/read/2012/2/21/extraparam/test.html转换为 http:/www.test.com/index.php/news/read/2012/2/21/extraparam/test.html
/**
* @$rule string 路由规则
* @$route string 规则映射的新地址
* @$regx string 地址栏pathinfo字符串
* @$extension stirng 伪静态拓展名
* return bool
*/
function parseUrlRule($rule,$route,$regx,$extension=null){
//去掉后缀名
!is_null($extension) && $regx = str_replace('.'.$extension,'',$regx);
//把路由规则和地址,分割到数组中,然后逐项匹配
$ruleArr = explode('/',$rule);
$regxArr = explode('/',$regx);
//$route以数组的格式传递,则取第一个
$url = is_array($route) ? $route[0] : $route;
$match =true;
//匹配检测
foreach($ruleArr as $key=>$value){
if(strpos($value,':')===0){
if(substr($value,-2)=='//d' && !is_numeric($regxArr[$key])){
$match = false;
新闻热点
疑难解答