0

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?

  • Does this answer your question? [Regex to disallow more than 1 dash consecutively](https://stackoverflow.com/questions/4897353/regex-to-disallow-more-than-1-dash-consecutively) – Nico Haase Sep 28 '21 at 05:29

2 Answers2

2

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

I would go with something like this.

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

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

Baldráni
  • 5,332
  • 7
  • 51
  • 79