Regex to get the current page or directory name?
I am trying to get the name of a page or last directory from a url
for example, if the url is: http://www.example.com/dir/
I want it to return dir
, or if the url passed in http://www.example.com/page.php
, I want it to return a page
Note. I don't need a trailing slash or file extension.
I've tried this:
$regex = "/.*\.(com|gov|org|net|mil|edu)/([a-z_\-]+).*/i";
$name = strtolower(preg_replace($regex,"$2",$url));
I ran this regex in PHP and didn't answer anything. (however I tested the same regex in ActionScript and it works!)
So what am I doing wrong here, how do I get what I want?
Thanks!!!
a source to share
And again, it seems that the problem here is not that your RegEx is not powerful enough, it is just sealed (closing delimiter in the middle of the line). I'll leave that for posterity, but I highly recommend you check out PHP parse_url()
.
This should provide:
substr($s = basename($_SERVER['REQUEST_URI']), 0, strrpos($s,'.') ?: strlen($s))
But this is better:
preg_replace('/[#\.\?].*/','',basename($path));
Although your example is short, so I can't tell if you want to keep the entire path or just the last element of it. The previous example will only keep the last snippet, but this should keep the entire path, being generic enough to work with pretty much anything that might be thrown to you:
preg_replace('~(?:/$|[#\.\?].*)~','',substr(parse_url($path, PHP_URL_PATH),1));
a source to share
As much as I personally like the use of regular expressions, the "harsher" (no better word) string functions might be a good alternative for you. The snippet below is used sscanf
to parse the portion of the URL path for the first group of letters.
$url = "http://www.example.com/page.php";
$path = parse_url($url, PHP_URL_PATH);
sscanf($path, '/%[a-z]', $part);
// $part = "page";
a source to share
This expression:
(?<=^[^:]+://[^.]+(?:\.[^.]+)*/)[^/]*(?=\.[^.]+$|/$)
Gives the following results:
http://www.example.com/dir/ dir
http://www.example.com/foo/dir/ dir
http://www.example.com/page.php page
http://www.example.com/foo/page.php page
Sorry in advance if this is not valid PHP regex - I tested it with RegexBuddy .
a source to share