Sami's code doesn't quite work. It checks for all alphanumerics or a single underscore.
Youre code doesn't quite work because its checking for a string that is exactly 3 characters long. The first is a character a-z, the second is 0-9 and the final is either a period or an underscore.
The following is my first pass. I'm not in a place where I can get to my interpreter right now but it might give you a starting point.
Code: Select all
<?php
if (ereg('^[A-Za-z0-9_][-A-Za-z0-9_]*(\.[A-Za-z0-9])?$',$string))
echo "Good";
else
echo "Bad";
?>
First. the enter regexp is surrounded with ^$ which "anchors" the string to the first and last character of the line, ie the entire string must be matched with nothing left over.
Then I require a single alphanumber or an underscore. (Depending on your OS a 0-9 may or may not be legal as a first character and a hyphen isn't in any I know of. Then zero of more other alphanumberics, hyphens, or underscores. Then I'm including a single option extension, which is a single period followed by alphanumberics.
This isn't a perfect regexp for all legal filenames, but it might be good enough depdning on what you need. (For instance a legal filename that fails is foo_bar.tar.gz, because of the multiple extensions.)