preg_match('/\.(?!pdf)$/', $file)
我要匹配除pdf文件以外的所有文件
path/file.jpg # match
path/file.png # match
path/file.pdf # not match
答案 0 :(得分:1)
您可以使用文件的扩展名来检查它是否为pdf,而不是使用正则表达式。
$ext = pathinfo($file, PATHINFO_EXTENSION);
if($ext != 'pdf'){
echo "I'm not a pdf";
}
如果您更喜欢使用正则表达式
<?php
$file = array("path/file.jpg", "path/file.png", "path/file.pdf");
foreach ($file as &$value) {
preg_match('/^(.(?!.*\.pdf$))*$/', $value, $matches);
if(!empty($matches)){
echo " $value is not a pdf";
}
}
答案 1 :(得分:1)
如果您想使用正则表达式,则可以使用该正则表达式:
^(?!.*\.pdf).*$
它只是使用否定的前瞻来断言文件名不是以.pdf
结尾,然后是.*
以匹配文件名中的所有内容。
在PHP中:
$filenames = array('path/file.jpg','path/file.png','path/file.pdf');
foreach ($filenames as $filename) {
if (preg_match('/^(?!.*\.pdf).*$/', $filename)) echo "\"$filename\" is not a PDF file.\n";
}
输出:
"path/file.jpg" is not a PDF file.
"path/file.png" is not a PDF file.
答案 2 :(得分:0)
断言在正则表达式中存在 的东西通常很奇怪,因为正则表达式通过查看输入内容中匹配的东西来工作。
您使用的方法是“零宽度否定的先行断言”-它匹配字符串中任何没有后跟pdf
的地方,但不会“耗尽“任何输入。因此您的正则表达式不起作用,因为它的其余部分仍需要匹配,即/\.$/
,表示“ .
位于字符串末尾”。
最简单的方法是查找做以.pdf
结尾的字符串,例如if ( ! preg_match('/\.pdf$/', $file) ) { ... }
。