gpt4 book ai didi

php - 西莱克斯 2 : RegEx in routing

转载 作者:行者123 更新时间:2023-12-04 16:45:56 25 4
gpt4 key购买 nike

是否可以在 Silex 2 路由中使用 RegEx?

我需要做这样的事情:

$this->get('/(adios|goodbay)', function (Request $request) use ($app) {
return $app['twig']->render('bye.html.twig', []);
})->bind('bye');

最佳答案

正如托马斯所说,是的,你可以。文档的重要部分是 route requirements :

In some cases you may want to only match certain expressions. You can define requirements using regular expressions by calling assert on the Controller object, which is returned by the routing methods.

例如:

$app->get('/blog/{postId}/{commentId}', function ($postId, $commentId) {
// ...
})
->assert('postId', '\d+')
->assert('commentId', '\d+');

因此,在您的情况下,路线的定义类似于:

$this->get('/{bye}', function (Request $request) use ($app) {
return $app['twig']->render('bye.html.twig', []);
})
->assert('bye', '^(adios|goodbye)$')
->bind('bye');

如果你还想知道参数的值,只需将其传递给 Controller ​​即可(参数名称必须与路由定义中的参数名称一致):

$this->get('/{bye}', function (Request $request, $bye) use ($app) {
if ($bye === 'adios') {
$sentence = "eso es todo amigos!";
}
else {
$sentence = "that's all folks!";
}

return $app['twig']->render('bye.html.twig', ["sentence" => $sentence]);
})
->assert('bye', '^(adios|goodbye)$')
->bind('bye');

关于php - 西莱克斯 2 : RegEx in routing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39045308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com