检查URL是否以Image Ext结尾

时间:2017-10-11 17:13:27

标签: php regex

我有preg_match()此处检查输入的值是否为URL

$regex = '_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS';
if (preg_match($regex, $string)) {
    echo "It is an Image URL";
} else {
    echo "It is not an Image URL";
}

我从Here获取它因为它显然具有最佳的验证结果,它太长而且我在RegEx中并不那么专业所以我试图在其中添加一个部分检查URL是否以图像扩展名结尾

所以我在.(?:jpg|gif|png)部分之前添加了以下规则?(?:/[^\s]*)?$_iuS,但是没有成功,我犯了什么错误?

1 个答案:

答案 0 :(得分:2)

为什么不使用适当的工具来完成这项工作:

$exts = array('jpg', 'gif', 'png');

if(filter_var($string, FILTER_VALIDATE_URL) &&
   in_array(strtolower(pathinfo($string, PATHINFO_EXTENSION)), $exts)) {
        echo "It is an Image URL";
} else {
        echo "It is NOT an Image URL";
}

filter_var有许多验证过滤器,pathinfo可以返回有关路径的信息。