1

I am trying to write a regular expression to validate file names on a file system.

Examples of valid file names are

  • tapa_newcougar_org.png
  • tapa_lamborghini-talk_com.png
  • tapa_clubfrontier_org.png

The logic behind valid is the image starts with tapa followed by an underscore. Then the domain name followed by _ the tld (com, org, net)

Thanks

Jonah
  • 9,991
  • 5
  • 45
  • 79
dnaluz
  • 135
  • 1
  • 10

3 Answers3

5
preg_match('/^tapa_[a-z0-9-_]+?_(com|org|net)\.png$/', $string);

That ought to do it (tested). If you want to match capital letters too, add the i (case insensitive) flag like this:

preg_match('/^tapa_[a-z0-9-_]+?_(com|org|net)\.png$/i', $string);

For a graphical representation of how this works, you can paste it in here: http://strfriend.com

Jonah
  • 9,991
  • 5
  • 45
  • 79
  • I don't do PHP regex so I don't know what makes it case insensitive (and the OP never specified it should be) but you won't match if the filename has capitals in it. – josh.trow Dec 13 '10 at 21:51
1

You could try:

preg_match('/^tapa_.+_(com|org|net)\.png$/', $filename);
Dan Dorman
  • 21
  • 2
0

^tapa_[a-zA-Z0-9\-_]+_(com|org|net)\.png$ should work for you.

Ryan Berger
  • 9,644
  • 6
  • 44
  • 56