Regular expression to filter filenames in PHP
I have strings that represent file paths. Something like this.
folder1/folderA/file1.flv folder2/folderB/file1.mp4 folder3/folderC/file1.jpg
I am trying to write an expression that basically matches against a list of valid extensions such as .flv
, .mp4
, .flv
I am sure I am way off 开发者_开发问答here but here's what I have .[(\.flv/)|(\.wmv/)|(\.mp4)]
comical, I'm sure... but hopefully shows the gist.
As an alternative to a regex, you could use pathinfo()
which will reliably get you the file extension from a path.
$allowed_extensions = array("flv", "mp4", "mpeg"); # note: all lowercase
$ext = pathinfo("/folder1/folderA/file1.flv", PATHINFO_EXTENSION);
# Search array of allowed extensions
if (in_array(strtolower($ext), $allowed_extensions))
echo "Okay";
else
echo "Fail";
If I interpret it correctly, you probably just want something like:
/[.](flv|mp4|wmv)$/
The $
ensures that it matches at the end of the string/filename. The alternatives are listed in the parens, and the [.]
is just a nicer notation for \.
$str = "folder1/folderA/file1.jpg";
$found = preg_match("/[.]+(jpg|flv)$/", $str, $returns);
print_r ($returns);
精彩评论