需要一个正则表达式来接受大于0和逗号的数值

i have to check a comma separated value in which i have to allow only numeric character greater than 0 and comma below is format that i required

  • -1,2,3,567,76,67,20,10

and below is the error that should not be accept by the regex

  1. 0,23,344 23,
  2. 0,2323,85 34
  3. 344,44,00
  4. sdfs,34,34,

i have used the regex

this one accept all numeric character and comma but also accept 0

return ( ! preg_match("/^([0-9,])+$/i", $quantity)) ? FALSE : TRUE;

this one accept not accept 0 at any place

return ( ! preg_match("/^([1-9,])+$/i", $quantity)) ? FALSE : TRUE;

For the sake of good readable and maintainable code I'd rather stick to a validation function - something like this:

function validateCsv($input)
{
    foreach (str_getcsv($input) as $value) {
        if (!preg_match('#^[\d]+$#', $value)) {
            throw new \Exception('invalid CSV-value ' . $value);
        }
        if ($value <= 0) {
            throw new \Exception('invalid CSV-value ' . $value);
        }
    }
}

This should do the work ^[1-9][0-9]*$

If you explode the comma-separated list, the test for validity of each element becomes much easier. Something like:

$values = explode(',', $input);
$invalidValues = array_filter($values, function($value) {
    // do your test and return TRUE if the value is invalid, so
    // the count of the resulting array will be 0 if all were valid
    return !is_numeric($value) || $value <= 0;
});

if (count($invalidValues) == 0) {
    // everything was valid, carry on
}

This also gives you a list of the invalid inputs, if that would be useful for providing error messages.