OrangeRind
OrangeRind

Reputation: 4818

Regex for finding valid filename

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()?

Upvotes: 16

Views: 25055

Answers (5)

richardevcom
richardevcom

Reputation: 1058

Here is an easy to use solution with specific file extensions:

$file = 'file-name_2020.png';
$extensions = array('png', 'jpg', 'jpeg', 'gif', 'svg');
$pattern = '/^[^`~!@#$%^&*()+=[\];\',.\/?><":}{]+\.(' . implode('|', $extensions). ')$/u';

if(preg_match($pattern, $discount)) {
    // Returns true
}

Keep in mind that special characters allowed in this scenario are only - and _. To allow more, just remove them from $pattern

Upvotes: 0

user3627897
user3627897

Reputation: 11

Below the regex using for checking Unix filename in a Golang program :

    reg := regexp.MustCompile("^/[[:print:]]+(/[[:print:]]+)*$")

Upvotes: 1

Tomalak
Tomalak

Reputation: 338248

The regex would be something like (for a three letter extension):

^[^/?*:;{}\\]+\.[^/?*:;{}\\]{3}$

PHP needs backslashes escaped, and preg_match() needs forward slashes escaped, so:

$pattern = "/^[^\\/?*:;{}\\\\]+\\.[^\\/?*:;{}\\\\]{3}$/";

To match filenames like "hosts" or ".htaccess", use this slightly modified expression:

^[^/?*:;{}\\]*\.?[^/?*:;{}\\]+$

Upvotes: 2

hegemon
hegemon

Reputation: 6764

$a = preg_match('=^[^/?*;:{}\\\\]+\.[^/?*;:{}\\\\]+$=', 'file.abc');

^ ... $ - begin and end of the string
[^ ... ] - matches NOT the listed chars.

Upvotes: 6

RichieHindle
RichieHindle

Reputation: 281525

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: "[^/?*:;{}\\]+"

Upvotes: 19

Related Questions