Delete files with special characters in filenames

前端 未结 4 677
渐次进展
渐次进展 2020-12-11 23:36

I need to delete old files with special characters in filenames like space,,,(,),! and so on via PHP. Classic unlin

相关标签:
4条回答
  • 2020-12-11 23:41

    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.

    0 讨论(0)
  • 2020-12-11 23:53

    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.

    0 讨论(0)
  • 2020-12-11 23:59

    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.

    0 讨论(0)
  • 2020-12-12 00:03

    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.

    0 讨论(0)
提交回复
热议问题