PHP 仅从 UNC 路径中提取文件名


PHP Extract only the Filename from UNC Path

我正在尝试创建一个内联网页面,该页面在UNC路径中查找所有pdf文档,并将它们作为在新窗口中打开的超链接返回列表中。我快到了,但是以下代码显示完整的UNC路径 - 我的问题如何仅显示文件名(最好没有.pdf扩展名)。我已经尝试了 basename 函数,但似乎无法获得正确的结果。

//path to Network Share
$uncpath = "//myserver/adirectory/personnel/";
//get all files with a .pdf extension.
$files = glob($uncpath . "*.pdf");
//print each file name
foreach ($files as $file) 
{
echo "<a target=_blank href='File:///$file'>$file</a><br>"; 
}

链接工作正常,只是显示文本显示//myserver/adirectory/personnel/document.pdf而不仅仅是document。请注意,上面的代码取自我在研究时发现的另一个示例。如果有全新的更好的方法,那么我愿意接受建议。

echo basename($file);

http://php.net/basename

像这样修改你的代码:

<?
$uncpath = "//myserver/adirectory/personnel/";
//get all files with a .pdf extension.
$files = glob($uncpath . "*.pdf");
//print each file name
foreach ($files as $file) 
{
echo "<a target=_blank href='File:///$file'>".basename($file)."</a><br>"; 
}
?>

如果 basename() 由于某种原因不起作用,您可以尝试这样做:

$file_a = explode('/',$file);
if (trim(end($file_a)) == '')
    $filename = $file_a[count($file_a)-2];
else
    $filename = end($file_a);