简体   繁体   English

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

[英]Regex replace non letters with '-', but leave any periods

I am trying to strip all non letters from a file path, but I need to leave the extension at the end.我试图从文件路径中删除所有非字母,但我需要在最后保留扩展名。

File example: $text = cat.jpg文件示例: $text = cat.jpg

I am current using this $text = preg_replace('/[^\\\\pL\\d]+/u', '-', $text);我目前使用这个$text = preg_replace('/[^\\\\pL\\d]+/u', '-', $text); Result: cat-jpg结果: cat-jpg

But this also converts any periods to a hyphen as well, I looked around and tried what I found from other posts, but they just removed the period all together.但这也会将任何句号转换为连字符,我环顾四周并尝试了我从其他帖子中找到的内容,但他们只是将句号一起删除了。

Help would be appreciated.帮助将不胜感激。

You can use this regex based on alternation and negative lookahead for your search:您可以根据交替和负前瞻使用此正则表达式进行搜索:

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

RegEx Demo正则表达式演示

RegEx Breakup:正则表达式分解:

[^\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

In PHP code:在 PHP 代码中:

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

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

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