views:

46

answers:

4

I have a little snippet that grab's the filename, including the extension.

$currURL = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);

given a url... http://www.somewebsite.com/pretty/url/here/this-is-a-page.php it returns this-is-a-page.php. I would like to be able to return simply, this-is-a-page.

I'm pretty obsessive about doing stuff like this in as little code as possible... how would you do this in a simple and elegant manner?

+2  A: 
$file_no_ext = preg_replace(
    array('#^.*/#', '#\.[^./]+$#'), '', parse_url($url, PHP_URL_PATH));

e.g.

http://example.com/fds.php/path/file
=> file
http://example.com/fds.php/path/file.php
=> file
http://example.com/fds.php/path/file.php2.php?abc=a
=> file.php2

Another solution is

$file_no_ext = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_FILENAME);
Artefacto
A: 
echo substr(strstr($url,'.php',TRUE),strrpos($url,'/')+1)

or

preg_match('/[^\/]+(?=\.php)/',$url,$match);
echo $match[0];
stillstanding
A: 

This works for .php files

rtrim(substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1),".php");

Derek Adair
+3  A: 

Try this:

$name = pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_FILENAME);

Test:

$arr = array('http://www.example.com/path/to/page.php',
             'http://www.example.com/path/to/page.php?a=b&c=d#e',
             'http://www.example.com/path/to/page.x.php',
             'www.example.com/path/to/page.php',
             '/path/to/page.php');

foreach ($arr as $str) {
    $name = pathinfo($str, PATHINFO_FILENAME);
    echo $name . '<br />';
}

Output:

page
page
page.x
page
page
GZipp
Artefacto
Well, I'm sorry to hear that, especially since it answers the question as stated. At least you found a bug in PHP's pathinfo().
GZipp