[英]regex matching url
在PHP中,klein路由將匹配盡可能多的路由。 我設置的2條路線存在沖突。 他們是:
$route1: '/websites/[i:websiteId]/users/[i:id]?'
和
$route2: '/websites/[i:websiteId]/users/[a:filename].[json|csv:extension]?'
這是我要匹配的URL,我認為應該匹配第一個而不是第二個:
/api/v1-test/websites/100/users/4
為這兩個生成的正則表達式為:
$regex1: `^/api(?:/(v1|v1-test))/websites(?:/(?P<websiteId>[0-9]++))/users(?:/(?P<id>[0-9]++))?$`
$regex2: `^/api(?:/(v1|v1-test))/websites(?:/(?P<websiteId>[0-9]++))/users(?:/(?P<filename>[0-9A-Za-z]++))(?:\.(?P<extension>json|csv))?$`
我的意思是,如果沒有“ .csv”或“ .json”,它就不匹配。 問題在於它同時匹配這兩個路由。 第二個結果文件名是“ 4”,擴展名是空白。
發送/api/v1-test/websites/100/users/users.csv可以正常工作,並且僅與第二條路由匹配。
我只能控制路由,而不能控制正則表達式或匹配項。 謝謝。
這一點
(?:\.(?P<extension>json|csv))?
在第二個正則表達式的末尾,使它匹配是否由於文件名而導致文件名?
在最后。 問號表示0 or 1 of the previous expression
。 擺脫它,至少,字符串只有在具有擴展名時才匹配此正則表達式。
要進行此更改,只需從第二條路線中刪除問號,如下所示:
$route2: '/websites/[i:websiteId]/users/[a:filename].[json|csv:extension]'
問題是match_type
確實定義了……很奇怪:
$match_types = array(
'i' => '[0-9]++',
'a' => '[0-9A-Za-z]++',
[...]
因此,您無法真正捕獲僅與[a-zA-Z]
對應的序列...我看到的唯一選擇是使用3條路線:
$route1: '/websites/[i:websiteId]/users/[i:id]?'
$route2: '/websites/[i:websiteId]/users/[a:filename]'
$route3: '/websites/[i:websiteId]/users/[a:filename].[json|csv:extension]'
並為路由2和3分配相同的操作,那么您將獲得:
/api/v1-test/websites/100/users/
匹配為1 /api/v1-test/websites/100/users/4
由1匹配 /api/v1-test/websites/100/users/test
由2匹配 /api/v1-test/websites/100/users/test.csv
由3匹配 這似乎是您想要的行為。
另一個(更簡單)的解決方案是利用文檔的以下內容:
Routes automatically match the entire request URI. If you need to match only a part of the request URI or use a custom regular expression, use the @ operator.
然后,您可以像這樣定義路線:
$route1: '@/websites/[0-9]+/users/[0-9]*$'
$route1: '@/websites/[0-9]+/users/[a-zA-Z]+(\.[a-zA-Z]+)?$'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.