i want to exclude all .mp3
and .jpeg
files (with a regular expression, not PHP). I know about !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. 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:
$disallowed = ['mp3', 'jpg', 'jpeg', /* more extensions */ ];
if (in_array(pathinfo($str, PATHINFO_EXTENSION), $disallowed)) {
# code...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.