Delete files with special characters in filenames

别说谁变了你拦得住时间么 提交于 2019-11-27 08:05:13

问题


I need to delete old files with special characters in filenames like space,,,(,),! and so on via PHP. Classic unlink($filename) does not work for these files. How can I transform filenames to filenames which accepts unlink function and filesystem? It's running on a Solaris machine and I don't have another access to it.


回答1:


How are you constructing the $filename? unlink should work on any filename with special characters if you do the normal escaping on it. e.g.

for a file with a name of this has, various/wonky !characters in it, then

 $filename = 'this has\, various\/wonky \!characters in it';
 unlink($filename);

should work.




回答2:


unlink accepts any valid string and will try to delete the file in that string.

unlink('/home/user1/"hello(!,');

Perhaps you are not properly escaping certain characters.




回答3:


You can also find all needed files and unlink them using RegexIterator:

<?php

$dir  = new RecursiveDirectoryIterator('.');
$iterator = new RecursiveIteratorIterator($dir);
$regex = new RegexIterator($iterator, '/(^.*[\s\.\,\(\)\!]+.*)/', RecursiveRegexIterator::GET_MATCH);

foreach ($regex as $file) {
        if (is_file($file[0])) {
                print "Unlink file {$file[0]}\n";
                unlink($file[0]);
        }
}

This code snippet recursively traverse all directories from current ('.') and matches all files by regex '/(^.[\s\,.()!]+.)/', then delete them.




回答4:


The way I do it in Linux is to use absolute paths, like "rm ./filename" that is dot slash.

You can also use escape charachters. Like "rm \-filename" that is - backspash hyphen.



来源:https://stackoverflow.com/questions/4557047/delete-files-with-special-characters-in-filenames

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!