Bobby W Bobby W - 8 months ago 33
PHP Question

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

I am current using this
$text = preg_replace('/[^\\pL\d]+/u', '-', $text);


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:


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:

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