PHP validate comma separated ids string

Use of regexp for validate comma separated ids string. Given regexp check and validate comma separated ids string.

REGEXP allows string only – if string has comma separated id or only id and not allow string – if string not in comma separated format or not only id or have other character except id and comma.

Here is given two code snippets for validate comma separated ids string.

How both regexp validate comma separated ids string?

  • Both string allow only 0-9 and comma in string.
  • Both string allow only 0-9 value string OR 0-9 comma separate string.
  • Snippet 2 not allow leading 0 in digit OR only 0 in string.
  • Snippet 1 allow leading 0 in digit OR only 0 in string

1) Snippet 1: php validate comma separated ids string

if(!preg_match('/^[0-9]+(,[0-9]+)*$/', $_GET['ids']))
    echo $_GET['ids'].' is invalid string';
else
    echo $_GET['ids'].' is valid string';

2) Snippet 2: php validate comma separated ids string

if(!preg_match('/^([1-9][0-9]*|[1-9])(,([1-9][0-9]+|[1-9]+))*$/', $_GET['ids']))
    echo $_GET['ids'].' is invalid string';
else
    echo $_GET['ids'].' is valid string';

Testing result for regexp:

1 = valid
10 = valid
1,10,199,2000,999999 = valid
blank = invalid
1a = invalid
1,10,199, = invalid
,1,10,199 = invalid

0 = valid (Snippet 1), invalid(Snippet 2)
1,010,0199 = valid (Snippet 1), invalid(Snippet 2)