Home > Back-end >  Regex for IMG filename
Regex for IMG filename

Time:09-29

I want to test if a img filename (jpg) is valid in PHP. The files should look like this:

test-file.jpg

test-123-test.jpg

123-456-thumbnail.jpg

I tried the following regex:

([a-z0–9-]) .(jpg)

It works fine, but still allows filnames like "test--123----.jpg", but I just want to allow one "-".

Any idea how to solve this?

CodePudding user response:

I would phrase the regex as:

^[a-z0-9] (?:-[a-z0-9] )*\.jpg$

Demo

This expresses a filename having one or more terms, each separated by a single hyphen.

CodePudding user response:

I would go with something like this.

^(\w ([-]{1})?) [.]jpg$

Here is a link for test purpose : https://regex101.com/r/Fo7b9c/1/

  • Related