I want to check whether a string is a file name (name DOT ext) or not.
Name of file cannot contain / ? * : ; { } \
Could you please suggest me the regex expression to use in preg_match()?
File name validation can be done by writing an appropriate regex pattern according to the file name requirements you have. For the purpose of this example, let’s assume that the file name may contain only letters, numbers, hyphens (“-“), underscores, dots (“.”), and spaces.
A regular expression to match valid filenames. It can be used to validate filenames entered by a user of an application, or the filename of files uploaded from a scanner. The expression ensures that your filename conforms to specific rules, including no leading or trailing spaces and no use of any characters besides the letters A-Z and numbers 0-9.
The third file name does not have an extension, similarly, the fourth file name only has an extension so both of them fail in the validation. The rest of the file names passed the regex validation as they fulfill all the criteria.
Valid file name mean it can contain lowercase letters, uppercase letters, digits, _ (underscore), - (hyphen), . (dot for ectension) and also can contain white spaces. Mean no special characters are allowed other than white spaces, underscore, hyphen and dot. There are some Mathes for example.
Here you go:
"[^/?*:;{}\\]+\\.[^/?*:;{}\\]+"
"One or more characters that aren't any of these ones, then a dot, then some more characters that aren't these ones."
(As long as you're sure that the dot is really required - if not, it's simply: "[^/?*:;{}\\]+"
$a = preg_match('=^[^/?*;:{}\\\\]+\.[^/?*;:{}\\\\]+$=', 'file.abc');
^ ... $ - begin and end of the string
[^ ... ] - matches NOT the listed chars.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With