开发者

Regex: extract first and last child directories from URL

开发者 https://www.devze.com 2023-04-12 10:57 出处:网络
I need a regular expression that matches two virtual folders; the first and the last in a given URL: www.example.com/first_folder/some/additional/bunch/of/folders/last_folder/

I need a regular expression that matches two virtual folders; the first and the last in a given URL:

www.example.com/first_folder/some/additional/bunch/of/folders/last_folder/

so far I have this regex: (?<!/)/[^/?#]+ but it matches all the folders :(

I need this for a rewrite rule to use in WordPress. A Quick and dirty example for rewriting http://mysite/project/1 into http://mysite/index.php?pagename=project&id=1:

$newrules = array();
$newrules['(project)/(\d*)$'] = 'index.php?pagename=$matc开发者_开发技巧hes[1]&id=$matches[2]';


Quick and dirty solution i.e. not thoroughly tested with the billion possible combinations of urls etc. so take it with a grain of salt..

.*?/(\w+)/.*?/(\w+)/$

Input :

www.example.com/first_folder/some/additional/bunch/of/folders/last_folder/

Output :

$1 prints first_folder
$2 prints last_folder
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号