Forum Moderators: coopster

Message Too Old, No Replies

PHP Parse Current Page URL

help parsing current page url

         

cookiemonster

3:15 am on Apr 24, 2010 (gmt 0)

10+ Year Member



Hi,

Is there any way to parse the current URL of a page to echo everything after the last / (slash), and before the extension? In other words, only the file name or folder name would be echoed.

For example,
http://www.example.com/coolfolder/document.php
would become document

http://www.example.com/folder
would become folder

Thanks in advance for any suggestions.

TheMadScientist

3:30 am on Apr 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



There are actually quite a few ways to do it, but the one that comes to mind off the top of my head is: (There might be an easier way with some built in function or something I'm not thinking of off the top of my head, but this is one way I might do it... I usually double check the manual and here using SEs before I 'just do' stuff I don't usually do to make sure there's not a 'better way' I'm not thinking of.)

$parts=explode('/',$_SERVER['REQUEST_URI']);
$last_part=end($parts);

if(strpos($last_part,'.')!==FALSE) {
$last_part=explode('.',$last_part);
$last_part=$last_part[0];
}

echo $last_part;

Or something to that effect...
I didn't test, but it should be close if it doesn't work as posted.

Readie

9:16 am on Apr 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Going by certain other recent posts we've had scientist, I feel obliged to share this method :)

preg_match('/([^\.\/]+)\./', $_SERVER['REQUEST_URI'], $out);
echo $out[1];

astupidname

5:15 pm on Apr 24, 2010 (gmt 0)

10+ Year Member



Another, more versatile method (lastPartUrl) which works with pretty much any url string which has a file or folder name after the domain parts:

<?php

function lastPartUrl($s, $returnExt = true) {
preg_match("/\/([^\/\.]+)(\/?|\.[^\/\.\?]*)(\?.*)?$/", $s, $m);
return ($m[1] !== null) ? (($returnExt) ? $m[1].$m[2] : $m[1]) : '';
}

$strArr = array(
'http://www.example.com/coolfolder/document.php?foo=bar',
'http://www.example.com/somefile.php',
'http://www.example.com/folder/?foo=bar',
'http://www.example.com/anotherFolder',
'http://www.example.com/',
'../rel/afile.php',
$_SERVER['REQUEST_URI']
);

foreach ($strArr as $str) {
$s = lastPartUrl($str);
$s2 = lastPartUrl($str, false);
if (strlen($s)) {
echo $s.' (with $returnExt passed as false:->) '.$s2.'<br>';
} else {
echo 'NO FILE OR FOLDER NAME FOUND<br>';
}
}

?>

cookiemonster

6:22 pm on Apr 24, 2010 (gmt 0)

10+ Year Member



Thank you astupidname - your method worked perfectly!
Exactly what I wanted!