我需要编写一个PHP函数来删除URL中的文件名。 [我不想简单地删除网址的最后一部分。因为某些网址会像http://www.examples.com/sample这样"样本"不能是一个文件。我只想删除文件名。
In. -> http://www.inforge.in/ongoing-works/main_project/index.html
Out -> http://www.inforge.in/ongoing-works/main_project/
In. -> http://www.inforge.in/ongoing-works/main_project/
Out -> http://www.inforge.in/ongoing-works/main_project/
In. -> http://www.inforge.in/ongoing-works/main_project
Out -> http://www.inforge.in/ongoing-works/main_project/
我认为解决方法是检查是否有'。' [dot]出现在最后一个' /'之后。如果是这样,请删除最后一个' /'之后的所有内容。但是没有得到用PHP编写它的逻辑
我无法简单地检查是否存在' .html',因为文件名可以是.php,.jpg,.jsp或类似的东西
答案 0 :(得分:1)
function stripFile($in){
$pieces = explode("/", $in); // split the URL by /
if(count($pieces) < 4) return $in . "/";
if(strpos(end($pieces), ".") !== false){ // we got a filename at the end
array_pop($pieces); // remove the filename
}elseif(end($pieces) !== ""){ // it ends with a name without an extension, i.e. a directory
$pieces[] = ""; // when $pieces is imploded, a "/" and then this "" will be appended
}
// else, already ends with a slash
return implode("/", $pieces);
}
答案 1 :(得分:0)
function removeFile($url){
$pieces = explode("/", $url); // split the URL by /
if(count($pieces) < 4) return $url. "/";
if(strpos(end($pieces), ".") !== false){ // we got a filename at the end
array_pop($pieces); // remove the filename
}elseif(end($pieces) !== ""){ // it ends with a name without an extension, i.e. a directory
$pieces[] = ""; // when $pieces is imploded, a "/" and then this "" will be appended
}
// else, already ends with a slash
return implode("/", $pieces);
}
答案 2 :(得分:0)
$lks = pathinfo("http://www.inforge.in/ongoingworks/main_project/index.html");
echo $lks['dirname'];