tags:

views:

71

answers:

1

I found this function that tests whether a string is Windows filename and folder friendly:

function is_valid_filename($name) {
    $parts=preg_split("/(\/|".preg_quote("\\").")/",$name);
    if (preg_match("/[a-z]:/i",$parts[0])) {
       unset($parts[0]);
    }
    foreach ($parts as $part) {
        print "part = '$part'<br>";
       if (preg_match("/[".preg_quote("^|?*<\":>","/")."\a\b\c\e\x\v\s]/",$part)||preg_match("/^(PRN|CON|AUX|CLOCK$|NUL|COMd|LPTd)$/im",str_replace(".","\n",$part))) {
          return false;
       }
    }
    return true;
 }

What I'd rather have is a function that strips all the bad stuff from the string. I tried to basically replace preg_match with preg_replace but no cigar.

+1  A: 

Following Gordon's reference, this gives:

$bad = array_merge(
        array_map('chr', range(0,31)),
        array("<", ">", ":", '"', "/", "\\", "|", "?", "*"));
$result = str_replace($bad, "", $filename);
Artefacto
It's more than that. For instance, the reserved names also have to be removed. Windows wont let you name a file `CON.PHP` - we all know it's a feature, dont we ;)
Gordon
@Gordon Actually the msdn doc page you linked to says `CON.PHP` is allowed, just discouraged.
Artefacto
@Artefacto try it. Create a new file, name it `CON.php`. Windows (Vista) will tell you it's an invalid device name and refuse to accept it. You can also do `CON.whatever`, same thing.
Gordon
@Gordon The fact that windows explorer doesn't let you means nothing. I could create such file with this program: http://pastebin.com/hAfp9s9h
Artefacto
@Artefacto might be, but the reference still explicitly states *Do not use the following reserved device names for the name of a file*. The recommendation is just for the reserved names plus extension, e.g. `con.php` is *not recommended*, while just `con` is *do not use*.
Gordon
@Gordon I was talking about `con.php` (that's what the program creates). Though now that you say it, I tested with `con` and it works too :p
Artefacto
@Artefacto I wouldnt be surprised if you manage to create filenames with any of the chars above either. All I'm saying is, the replacement above does not meet the given reference. And MSDN is official as can be.
Gordon
@Gordon Related: http://blogs.msdn.com/b/michkap/archive/2006/11/03/941420.aspx
Artefacto
@Artefacto good one
Gordon