问题
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