anyone can help me with a preg_match? I'd like to use php's preg_match to determine if an input is a valid filename or not (only the filename + file extension, not the full path). General rules:
1) f开发者_运维知识库ilename = a-z, A-Z, 0-9
2) extension = 3 or 4 letters
Thank you!
Try this:
preg_match('/^[a-zA-Z0-9]+\.[a-zA-Z]{3,4}$/', $filename)
You can do:
if(preg_match('#^[a-z0-9]+\.[a-z]{3,4}$#i',$filename)) {
echo "Valid";
}else{
echo "not Valid";
}
/^[a-zA-Z0-9]+\.[a-zA-Z]{3,4}$/
If you want to enforce min/max length for the file name part:
//minimum 4 characters and a maximum of 8 characters
/^[a-zA-Z0-9]{4,8}\.[a-zA-Z]{3,4}$/
^\w+\.\w{3,4}$
Should work.
Try this:
$filename1 = "file_16may25_001818.csv";
$filename2 = "file_16may25_001818";
$filename3 = "file.csv";
$filename4 = "file.txt";
echo "<br />filename1=>".preg_match('/^file(.*).csv/', $filename1);
echo "<br />filename2=>".preg_match('/^file(.*).csv/', $filename2);
echo "<br />filename3=>".preg_match('/^file(.*).csv/', $filename3);
echo "<br />filename4=>".preg_match('/^file(.*).csv/', $filename4);
?>
Output:
filename1=>1
filename2=>0
filename3=>1
filename4=>0
精彩评论