简体   繁体   English

使用PHP获取给定URL的文件名并删除文件扩展名

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

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 . 给定网址... http://www.somewebsite.com/pretty/url/here/this-is-a-page.php它返回this-is-a-page.php I would like to be able to return simply, this-is-a-page . 我希望能够简单地返回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));

eg 例如

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);
echo substr(strstr($url,'.php',TRUE),strrpos($url,'/')+1)

or 要么

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

这适用于.php文件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM