【问题标题】:str_replace in file names文件名中的 str_replace
【发布时间】:2012-11-07 17:37:18
【问题描述】:

我有一个 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); 

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

【问题讨论】:

    标签: php file directory str-replace


    【解决方案1】:

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

    由于您没有保存文件位置的代码,您可以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(),以防止&lt; 等字符破坏HTML 页面。所以,最终的结果是:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 2016-10-07
      • 1970-01-01
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多