[英]Exclude files using a regular expression
i want to exclude all .mp3
and .jpeg
files (with a regular expression, not PHP). 我想排除所有
.mp3
和.jpeg
文件(使用正则表达式, 而不是 PHP)。 I know about !preg_match
) 我知道
!preg_match
)
My example below always matches: 我下面的示例始终匹配:
$str = 'file.mp3'; // Exclude
$ex = '~(?!\.(mp3|jpe?g))$~';
if (preg_match($ex, $str)) {
echo "Match!";
} else {
echo "Nothing Match!";
}
Your negative lookahead isn't working because there is nothing to look ahead at. 您的否定前瞻不起作用,因为没有什么可以期待的。 Remember that lookaround assertions are zero-width — they do not actually consume characters.
请记住,环视断言是零宽度的-它们实际上并不消耗字符。 You will still need to account for the filename extension characters.
您仍然需要考虑文件扩展名字符。
Change the expression as follows: 更改表达式,如下所示:
$ex = '~(?!\.(mp3|jpe?g))[a-z]{3,4}$~';
A better approach would be to use pathinfo()
though. 更好的方法是使用
pathinfo()
。 Maintain an array of extensions that you'd like to disallow and then use in_array()
to check if the extension of the filename is in that array: 维护一个您要禁止的扩展名数组,然后使用
in_array()
检查文件名的扩展名是否在该数组中:
$disallowed = ['mp3', 'jpg', 'jpeg', /* more extensions */ ];
if (in_array(pathinfo($str, PATHINFO_EXTENSION), $disallowed)) {
# code...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.