简体   繁体   中英

Strip bad Windows filename characters

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.

Following Gordon's reference , this gives:

$bad = array_merge(
        array_map('chr', range(0,31)),
        array("<", ">", ":", '"', "/", "\\", "|", "?", "*"));
$result = str_replace($bad, "", $filename);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM