简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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