1

I need to validate images with regular expressions, with the following conditions:

  1. $string may be empty
  2. I can receive a single image with this format, for example: 2017-06-01-03-55-00-5930782c5c0b1.jpg
  3. I can get several image names separated by commas example: 2017-06-01-03-55-00-5930782c5c0b1.jpg, 2017-06-01-03-55-00-5930782c5c0b1.jpg
  4. Avoid other special characters other than these: A-Za-z0-9\-

I have managed to do this with my knowledge in regular expressions, but I have to validate, if the estring is empty, if there are several images separated by commas, and if there are no other characters than the string.

$pattern = '/[a-zA-Z0-9]\.(jpg|jpeg|png|gif)$/';
$string = '2017-06-01-03-55-00-5930782c5c0b1.jpg';

if( preg_match($pattern, $string) ) {
    echo "TRUE";
} else {
    echo "FALSE";
}

Thank you very much for your help, please.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Learning and sharing
  • 1,378
  • 3
  • 25
  • 45
  • check `empty()` then `explode()` on commas, then regular expression in array loop –  Jun 01 '17 at 23:23

2 Answers2

1

This will do all those things:

/^(?:[\dA-Za-z-]+\.(?:jpe?g|png|gif))?(?:, (?:[\dA-Za-z-]+\.(?:jpe?g|png|gif)))*$/

It will match the 2nd, 3rd, and 5th line of the following:

bad_image.jpg

2017-06-01-03-55-00-5930782c5c0b1.jpg
2017-06-01-03-55-00-5930782c5c0b1.jpeg, bad_image.jpg
2017-06-01-03-55-00-5930782c5c0b1.png, 2017-06-01-03-55-00-5930782c5c0b1.gif

Here is the Demo. My pattern will match zero or more valid image filenames which must be separated by comma-space

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
0

I think you might be looking for the following, since your regex pattern didn't account for the dashes.

/[a-z0-9-]+\.(jpg|jpeg|png|gif)/gi

A great resource for perfecting your regex can be found at Regexr.com

The /g at the end of the expression makes the pattern global, looking at the whole string passed to it rather than finding the first match and stopping.

The /i at the end of the expression means case insensitive so that you don't have to include both a-z and A-Z.

Eddy Jones
  • 43
  • 5