Search code examples
phpregexpreg-matchpreg-match-allregex-group

How to check if the string is in proper array format with regex?


I want to check if the string is proper array structure for example:

"[0,1,2,3,4,5,6,7,8,9]"

I want regex that should match square brackets at the start [ and end ] and within square brackets, it should only contain the digits 0-9 and comma ,. Same as like above i.e. array of digits but it's a string.

I tried the following:

/\[\d+\]/

But it's not working for commas ,.

Edited:

I am receiving "[0,1,2,3,4,5,6,7,8,9]" as a string from POST method.


Solution

  • Obviously not regex at all, but you'll end up with the array of ints you want, and no runtime errors.

    if (is_array($array = json_decode($string)) && array_filter($array, 'is_int') == $array) {
        // $string is a properly formatted array of ints, now in $array. Do stuff with it
    } else {
        // $string is something else, return an error or whatever
    }