我有一个抓取文件名的小片段,包括扩展名。
$currURL = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
给定一个网址... http://www.somewebsite.com/pretty/url/here/this-is-a-page.php
,它会返回this-is-a-page.php
。我希望能够简单地返回this-is-a-page
。
我非常痴迷于用尽可能少的代码做这样的事情......你怎么能以简单而优雅的方式做到这一点?
答案 0 :(得分:4)
试试这个:
$name = pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_FILENAME);
测试:
$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 />';
}
输出:
page
page
page.x
page
page
答案 1 :(得分:2)
$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
另一种解决方案是
$file_no_ext = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_FILENAME);
答案 2 :(得分:0)
echo substr(strstr($url,'.php',TRUE),strrpos($url,'/')+1)
或
preg_match('/[^\/]+(?=\.php)/',$url,$match);
echo $match[0];
答案 3 :(得分:0)
这适用于.php文件
rtrim(substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1),".php");