200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > php正则匹配路由 url路由正则表达式PHP

php正则匹配路由 url路由正则表达式PHP

时间:2020-01-25 10:23:56

相关推荐

php正则匹配路由 url路由正则表达式PHP

我正在编写一个处理

PHP Web服务路由的类,但我需要更正正则表达式,我想知道解析url的最有效方法是什么.

示例网址:

> POST /用户

> GET /用户

> 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();

目标变量现在包含一个数组:

>方法

>网址

>回调方法

这是我到目前为止所得到的:

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];

}

我非常感谢所有的帮助,非常感谢.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。