正则表达式用' - '替换非字母,但保留任何句点

时间:2016-09-23 17:09:26

标签: php regex

我试图从文件路径中删除所有非字母,但我需要将扩展​​名留在最后。

文件示例: $text = cat.jpg

我目前正在使用此$text = preg_replace('/[^\\pL\d]+/u', '-', $text); 结果:cat-jpg

但是这也将任何句号转换为连字符,我环顾四周并尝试从其他帖子中找到的内容,但他们只是将所有句点一起删除。

帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以根据替换和否定前瞻使用此正则表达式进行搜索:

[^\pL\pN.]+|\.(?![^.]+$)

RegEx Demo

RegEx分手:

[^\pL\pN.]+  # Search 1 or more of any char that is not DOT and letter and number (unicode)
|            # OR
\.           # search for DOT
(?![^.]+$)   # negative lookahead to skip DOT that is just before file extension

在PHP代码中:

$text = preg_replace('/[^\pL\pN.]+|\.(?![^.]+$)/u', '-', $text);