url的正则 php,Url路由正则表达式PHP

我正在编写一个类来处理我的PHP web服务的路由,但我需要纠正这个正则表达式,并且我想知道什么才是解析url最有效的方法。

示例网址:

POST /使用者

GET / users

GET / users& limit = 10& offset = 0

GET / users / search& keyword = Richard

GET / users / 15 / posts / 38

我想在PHP中为类创建的是:

$router = new Router();

$router->addRoute('POST', '/users', function(){});

$router->addRoute('GET', '/users/:uid/posts/:pid', function($uid, $pid){});

$target = $router->doRouting();目标变量现在将包含一个数组:

方法

URL

回叫方法

这是我到目前为止:

class Router{

use Singleton;

private $routes = [];

private $routeCount = 0;

public function addRoute($method, $url, $callback){

$this->routes[] = ['method' => $method, 'url' => $url, 'callback' => $callback];

$this->routeCount++;

}

public function doRouting(){

$reqUrl = $_SERVER['REQUEST_URI'];

$reqMet = $_SERVER['REQUEST_METHOD'];

for($i = 0; $i < $this->routeCount; $i++){

// Check if the url matches ...

// Parse the arguments of the url ...

}

}

}所以我首先需要一个正则表达式:

/ mainAction /:argumentName / secondaryAction /:secondaryActionName

检查它是否与$ reqUrl匹配(参见上面的for循环)

提取参数,所以我们可以在回调函数中使用它们。

我自己试了一下:

(code should be in the for loop @ doRouting function)

// Extract arguments ...

$this->routing[$i]['url'] = str_replace(':arg', '.+', $this->routing[$i]['url']);

// Does the url matches the routing url?

if(preg_match('#^' . $this->routes[$i]['url'] . '$#', $reqUrl)){

return $this->routes[$i];

}我非常感谢所有帮助,非常感谢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值