(文件名特殊字符过滤)文件夹或文件名字中不能使用的特殊字符共有9个,过滤文件名中的特殊字符,并处理过滤后长度为0的情况

zblog2年前zblog问题解答113
# 过滤文件名中的特殊字符,并处理过滤后长度为0的情况
function guiyi_txt_sanitize_file_name($fileName)
{
    // 定义不允许的特殊字符
    $invalidChars = array('\\', '/', ':', '*', '?', '"', '<', '>', '|');

    // 使用 str_replace 过滤掉不允许的字符
    $sanitizedFileName = str_replace($invalidChars, '', $fileName);

    // 如果过滤后的文件名为空,则返回 "未命名"
    if (empty(trim($sanitizedFileName))) {
        return '未命名';
    }
    return $sanitizedFileName;
}

文件夹或文件名字有一些特殊字符是不能使用的 一共有几个 特殊字符 不能用


文件夹或文件名字中不能使用的特殊字符共有9个,

具体为:

\(反斜杠)

/(正斜杠)

:(冒号)

*(星号)

?(问号)

"(双引号)

<(小于号)

>(大于号)

|(竖线)



(文件名特殊字符过滤)文件夹或文件名字中不能使用的特殊字符共有9个,过滤文件名中的特殊字符,并处理过滤后长度为0的情况


参考  https://zblog.gongshi5.com/post/109.html  



python 实现

def guiyi_txt_sanitize_file_name(file_name):
    # 定义不允许的特殊字符集合(使用集合提升查找效率)
    invalid_chars = {'\\', '/', ':', '*', '?', '"', '<', '>', '|'}

    # 使用生成器表达式过滤字符(更高效的方式)
    sanitized_file_name = ''.join([c for c in file_name if c not in invalid_chars])

    # 清理空白字符并处理空字符串情况
    sanitized_file_name = sanitized_file_name.strip()
    return '未命名' if not sanitized_file_name else sanitized_file_name


print(guiyi_txt_sanitize_file_name("test\\file :name.txt"))  # 输出: testfilename.txt
print(guiyi_txt_sanitize_file_name("  *invalid?:/ "))  # 输出: 未命名
print(guiyi_txt_sanitize_file_name("valid file.txt"))  # 输出: valid file.txt
print(guiyi_txt_sanitize_file_name("   "))  # 输出: 未命名


相关文章

mysql数据库坏了 linux启动不了  ib_logfile0 和 ib_logfile1

mysql数据库坏了 linux启动不了 ib_logfile0 和 ib_logfile1

mysql数据库坏了 linux启动不了把 ib_logfile0 和 ib_logfile1 删除或重命名 重新启动 (数据损坏了 ,可以事后重新导入)...

(zb表名字)zblog获取系统表的名字 $zbp->table[$tableNameShort]

直接复制把! $zbp->table['Post'] # 文章/页面 输出: zbp_post  (字符串类型) $z...

php require_once 包含文件不显示不执行不报错 就是空白,原因是 函数名字重复了。。。

php require_once 包含文件不显示不执行不报错 就是空白,原因是 函数名字重复了。。。每个插件 以插件名字 命名函数  或者以 插件名字开头的 类的静态函数 组织函数...

linux修改密码 ssh端口查看

查看ssh端口 cat /etc/ssh/sshd_config | grep Port 修改密码 passwd...

php读取文件夹 phptxt 扫描txt文件效率 对比

# 获取一个 txt 文件中的txt文件数量(一层) function guiyi_txt_pro_txt_num2($path_txt) { &nb...

linux时间错误 centos时间错误

timedatectl set-timezone Asia/Shanghai echo "Asia/Shanghai" | ...