str_replace在文件名中

时间:2012-11-07 17:37:19

标签: php file directory str-replace

我有一个PHP代码,用于显示列表中目录的文件内容。每个文件都是链接的,因此如果单击,它将下载或打开。目录中的文件将是客户上传的文件。如果文件名包含空格,则链接已断开且无法打开,因此我希望将空格替换为下划线。

我知道str_replace正在寻找我正在寻找的东西,但我不知道如何将它应用于这段代码(我没写过)。

// Define the full path to your folder from root 
$path = "uploads/artwork"; 


// Open the folder 
$dir_handle = @opendir($path) or die("Unable to open $path"); 

// Loop through the files 
while ($file = readdir($dir_handle)) { 

if($file == "." || $file == ".." || $file == "index.php" ) 

    continue; 
    echo "<a href=uploads/artwork/$file>$file</a><br />"; 

} 
// Close 
closedir($dir_handle); 

非常感谢所有帮助。谢谢!

1 个答案:

答案 0 :(得分:5)

当您将文件名保存到服务器时,也必须用下划线替换文件名。

由于您没有保存文件的位置的代码,因此您可以urlencode()链接URL,以免被危险字符破坏。请注意,最初它被空格打破,因为您没有用引号括起href值,我在这里做:

echo "<a href='" . urlencode("uploads/artwork/$file") . "'>$file</a><br />";

否则,要用下划线替换空格,你可以这样做:

echo "<a href=" . str_replace( ' ', "_", "uploads/artwork/$file") . ">$file</a><br />";

但同样,这可能需要您在上传时更改文件名。

请注意,您还需要在该链接的$file部分调用htmlentities(),以防止<等字符破坏HTML页面。所以,最终结果将是:

echo "<a href='" . urlencode("uploads/artwork/$file") . "'>" . htmlentities( $file) . "</a><br />";