numediaweb
numediaweb

Reputation: 17010

Regex: extract first and last child directories from URL

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=$matches[1]&id=$matches[2]';

Upvotes: 1

Views: 2103

Answers (1)

FailedDev
FailedDev

Reputation: 26930

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

Upvotes: 2

Related Questions