preg_match for a list of files extension

狂风中的少年 提交于 2019-12-25 08:56:28

问题


I would like to have your opinion on a simple regular expression I built to verify a list of comma separated file extensions (there could also be one or multiple spaces after or before the comma character).

This regular expression should return the following values:

$list = 'jpg,png,gif'; // valid
$list = 'jpg   , png, gif'; // valid
$list = 'jpg'; // valid
$list = 'jpg, png, gif'; // valid
$list = 'jpg png, gif'; // INVALID
$list = 'jpg png'; // INVALID

I am using the regular expression below, what do you think of it? can it optimized or shortened?

if(!preg_match( '#^[0-9a-zA-Z]+([ ]*,[ ]*[0-9a-zA-Z]+)*$#' , $list))
{
    echo 'invalid extension list';
} else{
    echo 'valid extension list';
}

Thanks for your good advices


回答1:


You can also shorten it a bit:

preg_match('#^\w+(\s*,\s*\w+)*$#' , $list)



回答2:


Maybe an easier way would be to split by , and see if any of the results contain space(s).

function isvalid($var)
{
    return !strpos ($var, ' ');
}

$array = explode (',', $list);
$array_filtered = array_filter ($array, 'isvalid');

if ($array == $array_filtered) {
    echo 'Valid';
}
else {
    echo 'Invalid';
}

This should be way faster than using a regex.



来源:https://stackoverflow.com/questions/10563796/preg-match-for-a-list-of-files-extension

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!