我想检查字符串是否是正确的数组结构,例如:
"[0,1,2,3,4,5,6,7,8,9]"
我希望正则表达式应该与开头 [
和结尾 ]
处的方括号匹配,并且在方括号内,它应该只包含数字 0-9
和逗号 ,
。与上面相同,即数字数组,但它是一个字符串。
我尝试了以下方法:
/\[\d+\]/
但它不适用于逗号 ,
。
已编辑:
我从 POST
方法接收 "[0,1,2,3,4,5,6,7,8,9]"
作为字符串。
最佳答案
显然根本不是正则表达式,但您最终会得到所需的整数数组,并且不会出现运行时错误。
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
}
关于php - 如何使用正则表达式检查字符串是否采用正确的数组格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57718199/