简体   繁体   English

删除所有非单词字符,但“。”

[英]Remove all non-word characters but “.”

What is the easiest way to remove all non-word characters of a filename? 删除文件名中所有非单词字符的最简单方法是什么?

The dot at the end before the extension is obviously needed, so all symbols like " - " or " * " or " ? " should be removed except " . " 显然需要在扩展之前的末尾处的点,因此除了“ . ”之外的所有符号应该被删除,如“ - ”或“ * ”或“ ?.

Something like this: 像这样的东西:

$filename = preg_replace("/[^\.]\W/", "", $filename);

Why not: 为什么不:

$filename = preg_replace('/[^.\w]/', '', $filename);

This will simply remove any character that is not a word character or period. 这将删除任何不是单词字符或句点的字符。

I would use something like that: 我会用这样的东西:

$filename = preg_replace("/\W(?=.*\.[^.]*$)/", "", $filename);

The regex will match any non-word character ('word character' here is defined by the class [a-zA-Z0-9_] ) from a filename as long as there's a period for the extension. 正则表达式将匹配文件名中的任何非单词字符(此处的“单词字符”由类[a-zA-Z0-9_] ),只要存在扩展名即可。

This will also take into consideration possible file names such as file.name.txt and correctly return filename.txt (the first dot not being the dot for file extension). 这也将考虑可能的文件名,例如file.name.txt并正确返回filename.txt (第一个点不是文件扩展名的点)。

My preference is 我的偏好是

$filename = preg_replace('/[^.a-zA-Z]/', '', $filename);

If you want to add the digits too, then 如果你想要添加数字,那么

$filename = preg_replace('/[^.a-zA-Z0-9]/', '', $filename);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将字符串拆分为多个部分,同时保留所有非单词字符 - Splitting string into sections while maintaining all non-word characters 仅包含非单词字符的字符串匹配的正则表达式 - Regular expression that matches a string only if it contains non-word characters 对于以非单词字符开头或结尾的单词的单词边界的自定义定义 - Custom definition for word boundary for words that begin or end with non-word characters 删除或重复的非单词字符(如HTML文本区域中的换行符)会导致modsecurity错误 - Removal or repetitive non-word characters like line breaks in a HTML textarea that cause errors in modsecurity 如何删除字符串中的所有不可打印字符? - How to remove all non printable characters in a string? 正则表达式删除非字母数字字符和点后的所有字符? - Regex to remove non-alphanumeric characters and all characters after dot? PHP Regex —删除字符串中最后一个单词之外的所有字符 - PHP Regex — Remove all characters but first from last word in string 删除所有特殊字符,但不删除非拉丁字符 - Remove all special chars, but not non-Latin characters 正则表达式删除除表情符号以外的所有非字母数字字符 - regex remove all non alphanumeric characters except emoticons 使用preg_replace删除所有非字母数字字符 - Remove all non-alphanumeric characters using preg_replace
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM