开发者

get the filename of a given URL using PHP and remove the file extension

开发者 https://www.devze.com 2023-01-11 08:43 出处:网络
I have a little snippet that grab\'s the filename, including the extension. $currURL = substr($_SERVER[\"SCRIPT_NAME\"],strrpos($_SERVER[\"SCRIPT_NAME\"],\"/\")+1);

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-p开发者_如何学JAVAage.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?


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


$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);


This works for .php files

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


echo substr(strstr($url,'.php',TRUE),strrpos($url,'/')+1)

or

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

精彩评论

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