简体   繁体   中英

php regex filename

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) filename = a-z, A-Z, 0-9
2) extension = 3 or 4 letters

Thank you!

尝试这个:

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}$

应该管用。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM