File PHP dirname()丢失最后一个文件夹 问题

File PHP dirname()丢失最后一个文件夹 问题,file,path,explode,dirname,File,Path,Explode,Dirname,这是一个很容易理解的问题 例如,我让用户提交一个URL“http://example.com/path/filename.html“ 我正在使用PHP的dirname()函数来获取这个URL的所谓“base”。对于上述示例,这将是“http://example.com/path“ 当用户输入以下内容时,我的问题出现: http://example.com/blog 如果在浏览器中键入上述内容,您将在名为“blog”的文件夹中看到index.php或.html页面。但是,PHP的dirname(

这是一个很容易理解的问题

例如,我让用户提交一个URL“http://example.com/path/filename.html“

我正在使用PHP的
dirname()
函数来获取这个URL的所谓“base”。对于上述示例,这将是“http://example.com/path“

当用户输入以下内容时,我的问题出现:

http://example.com/blog
如果在浏览器中键入上述内容,您将在名为“blog”的文件夹中看到index.php或.html页面。但是,PHP的
dirname()
将只返回“http://example.com“

我不确定它是否认为“blog”是一个无扩展名的文件(如果存在的话),但我真的找不到解决方案

我尝试过的事情 我首先尝试使用以下快速方法获取URL的扩展名:

$url = 'http://example.com/index.php';
$file_extension = end(explode('.', $filename));
然后,我将使用PHP
empty()
检查扩展是否存在。如果扩展名存在,则表示在文件夹后面输入了文件名,例如“http://example.com/path/file.html“,并且
dirname()
非常完美。如果扩展名不存在,则不会输入任何文件,并且路径中的最后一项是文件夹,因此它已经是“基础”

但是,在“简单”的情况下http://example.com/path/,上面的将返回“.com/path/”作为文件扩展名,我们都知道它不存在。在本例中,我将使用
dirname()
函数并切断“/path/”

编辑:

使用
basename($url)
的扩展名将不起作用,因为如果用户输入“http://example.com
basename()
返回“example.com”,其扩展名应该是 “.com”

希望有人也遇到过同样的问题,并且知道解决方法。我仍在寻找,但任何答案都将不胜感激 编辑 好的,在我放弃之前的最后一次:

function getPath($url){
    $parts=explode("/",$url);
    $patharray=array(".","http:","https:");
    if(!in_array(pathinfo($url,PATHINFO_DIRNAME),$patharray) && strpos($parts[count($parts)-1], ".")!==false)
        unset($parts[count($parts)-1]);
    $url=implode("/",$parts);
    if(substr($url,-1)!='/')
        $url.="/";
    return $url;
}
echo getPath("http://www.google.com/blog/testing.php")."\n";
echo getPath("www.google.com/blog/testing.php")."\n";
echo getPath("http://www.google.com/blog/")."\n";
echo getPath("http://www.google.com/blog")."\n";
echo getPath("http://www.google.com")."\n";
echo getPath("http://www.google.com/")."\n";
echo getPath("www.google.com/")."\n";
echo getPath("www.google.com")."\n";
任何最后一部分带有“.”的url都会被解析出来,否则它将被单独保留。它使用
pathinfo()
检查它是否只是一个域(“google.com”或http://www.google.com),然后保留最后一部分,因为其中会有一个“.”。 以下是脚本输出:

http://www.google.com/blog/
www.google.com/blog/
http://www.google.com/blog/
http://www.google.com/blog/
http://www.google.com/
http://www.google.com/
www.google.com/
www.google.com/

看起来不错,但当我尝试最底层的代码时,它在
$parsed['path']
中包含了“index.html”。谢谢你的帮助。@apparatix修复了它。很抱歉,它不起作用,但已测试。很抱歉再次拒绝您,但使用“”将只返回没有“blog”的域。虽然我同意把“/”放在
dirname
Awesome之后!谢谢你的尝试哈哈。试过了,效果很好。我注意到使用不带尾随斜杠的域,例如“example.com”会被截断。但是,添加尾部斜杠可以解决问题。谢谢