4

所有平台(可能还有文件系统)对于允许哪些字符作为文件名或目录名都有不同的规则。此外,一些系统有一个文件名黑名单:例如在 Windows 上,com1是一个无效的文件名。

有没有办法以编程方式知道在 PHP 中计算有效文件名的规则?

作为替代方案,是否有一个可信赖的安全字符列表,除了[0-9a-zA-Z]?

请注意,基于尝试保存的解决方案(如果失败,则文件名无效)不适用于我的用例。

4

1 回答 1

2

已经回答得很好,清理字符串以使它们的 URL 和文件名安全?

我在Chyrp代码中发现了这个更大的函数:

/**
 * Function: sanitize
 * Returns a sanitized string, typically for URLs.
 *
 * Parameters:
 *     $string - The string to sanitize.
 *     $force_lowercase - Force the string to lowercase?
 *     $anal - If set to *true*, will remove all non-alphanumeric characters.
 */
function sanitize($string, $force_lowercase = true, $anal = false) {
    $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
                   "}", "\\", "|", ";", ":", "\"", "'", "‘", "’", "“", "”", "–", "—",
                   "—", "–", ",", "<", ".", ">", "/", "?");
    $clean = trim(str_replace($strip, "", strip_tags($string)));
    $clean = preg_replace('/\s+/', "-", $clean);
    $clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;
    return ($force_lowercase) ?
        (function_exists('mb_strtolower')) ?
            mb_strtolower($clean, 'UTF-8') :
            strtolower($clean) :
        $clean;
}

这个在wordpress代码中

/**
 * Sanitizes a filename replacing whitespace with dashes
 *
 * Removes special characters that are illegal in filenames on certain
 * operating systems and special characters requiring special escaping
 * to manipulate at the command line. Replaces spaces and consecutive
 * dashes with a single dash. Trim period, dash and underscore from beginning
 * and end of filename.
 *
 * @since 2.1.0
 *
 * @param string $filename The filename to be sanitized
 * @return string The sanitized filename
 */
function sanitize_file_name( $filename ) {
  $filename_raw = $filename;
  $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`",
  "!", "{", "}");
  $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw);
  $filename = str_replace($special_chars, '', $filename);
  $filename = preg_replace('/[\s-]+/', '-', $filename);
  $filename = trim($filename, '.-_');
  return apply_filters('sanitize_file_name', $filename, $filename_raw);
}

2012 年 9 月更新

Alix Axel在这方面做了一些令人难以置信的工作。他的 punction 框架包括几个很棒的文本过滤器和转换。

于 2013-07-15T03:59:05.433 回答