Php regex file name

Can anyone help me with preg_match? I would like to use php preg_match to determine if the input is a valid file name or not (only the file name + file extension, not the full path). General rules:

1) filename = a-z, A-Z, 0-9
2) extension = 3 or 4 letters

Thank!

+3
source share
5 answers

Try the following:

preg_match('/^[a-zA-Z0-9]+\.[a-zA-Z]{3,4}$/', $filename)
+5
source

You can do:

if(preg_match('#^[a-z0-9]+\.[a-z]{3,4}$#i',$filename)) {
        echo "Valid";
}else{
        echo "not Valid";
}
+4
source
/^[a-zA-Z0-9]+\.[a-zA-Z]{3,4}$/

If you want to provide a minimum / maximum length for part of the file name:

//minimum 4 characters and a maximum of 8 characters

/^[a-zA-Z0-9]{4,8}\.[a-zA-Z]{3,4}$/
+1
source
^\w+\.\w{3,4}$

Must work.

+1
source

Try the following:   

$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);

?>

Conclusion:

filename1=>1
filename2=>0
filename3=>1
filename4=>0
0
source

Source: https://habr.com/ru/post/1743773/


All Articles