Slim 3 将特定的正则表达式配置到路由中
Slim 3 Configure specific regex into route
我有一个正则表达式:^(profile\/\~)(:\([0-9a-z,-]+\))?$
这允许像这样的字符串:profile/~
或 profile/~:(var1,var2,var3,...)
我需要将此正则表达式配置为 Slim 路由以接受以下路由。
http://example.com/v1/profile/~:(var1, var2)
http://example.com/v1/profile/~:
我的PHP代码:
$app = new \Slim\App;
$app->group('/v1', function () {
$this->get('/profile/~[:[{fields:[0-9a-z,-]+}]]', function ($request, $response, $args) {
$name = $request->getAttribute('name');
$response->getBody()->write("Hello " . $args['fields']);
return $response;
})->setName('profile');
});
$app->run();
有没有办法将该正则表达式转换为与 slim 兼容的正则表达式?
我做了一些研究,但无法测试。请尝试以下操作,并就哪些有效,哪些无效给我一些反馈。
我不清楚 var1
和 var2
是什么。他们是名字和姓氏吗?他们是2个独立的用户名吗?如果它们以逗号分隔,为什么您的正则表达式允许变量包含逗号?
下面的方法将假设非空字符串将被包裹在括号中,并且捕获的字符串就像 "FirstName, LastName" 一样作为单个字符串。 (如果不是,则在 trim()
括号后的逗号处展开。)
未测试代码:(需要匹配,但整个子字符串是 "optional")
$app = new \Slim\App;
$app->group('/v1', function () {
$this->get('/profile/~:{params:\(?[^,]*,?[^)]*\)?}',function($request,$response,$args){
// required capture-^ ^^^-optional()-^^^
if(strlen($name=$request->getAttribute('params'))){
$greeting='Hello ',substr($name,1,-1);
}else{
$greeting='Hello';
}
$response->getBody()->write($greeting);
return $response;
})->setName('profile');
});
$app->run();
我有一个正则表达式:^(profile\/\~)(:\([0-9a-z,-]+\))?$
这允许像这样的字符串:profile/~
或 profile/~:(var1,var2,var3,...)
我需要将此正则表达式配置为 Slim 路由以接受以下路由。
http://example.com/v1/profile/~:(var1, var2)
http://example.com/v1/profile/~:
我的PHP代码:
$app = new \Slim\App;
$app->group('/v1', function () {
$this->get('/profile/~[:[{fields:[0-9a-z,-]+}]]', function ($request, $response, $args) {
$name = $request->getAttribute('name');
$response->getBody()->write("Hello " . $args['fields']);
return $response;
})->setName('profile');
});
$app->run();
有没有办法将该正则表达式转换为与 slim 兼容的正则表达式?
我做了一些研究,但无法测试。请尝试以下操作,并就哪些有效,哪些无效给我一些反馈。
我不清楚 var1
和 var2
是什么。他们是名字和姓氏吗?他们是2个独立的用户名吗?如果它们以逗号分隔,为什么您的正则表达式允许变量包含逗号?
下面的方法将假设非空字符串将被包裹在括号中,并且捕获的字符串就像 "FirstName, LastName" 一样作为单个字符串。 (如果不是,则在 trim()
括号后的逗号处展开。)
未测试代码:(需要匹配,但整个子字符串是 "optional")
$app = new \Slim\App;
$app->group('/v1', function () {
$this->get('/profile/~:{params:\(?[^,]*,?[^)]*\)?}',function($request,$response,$args){
// required capture-^ ^^^-optional()-^^^
if(strlen($name=$request->getAttribute('params'))){
$greeting='Hello ',substr($name,1,-1);
}else{
$greeting='Hello';
}
$response->getBody()->write($greeting);
return $response;
})->setName('profile');
});
$app->run();