php - 如何使用正则表达式检查字符串是否采用正确的数组格式?

标签 php regex preg-match preg-match-all regex-group

我想检查字符串是否是正确的数组结构,例如:

"[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/

相关文章:

php - 特定英国邮政编码区号所需的 preg_match 正则表达式

php - 如何在用户登录时显示用户特定功能?

php - 从 mysql 数据库检索预览时损坏

php - 在 PHP 应用程序的 gettext 中使用多个域

regex - 为什么 "\w"不匹配 Perl 正则表达式中的 Unicode 单词字符(例如 "ğ,İ,ş,ç,ö,ü")?

regex - 正则表达式字符类中的空格产生奇怪的结果

php - 如何在随机位置精确匹配 [A-Za-z]?

php - Laravel - 如何在 Blade View 中计算数组中对象的总和

php - preg_match_all `u` 标志依赖于什么?

php - WordPress 中的 preg_match 未知修饰符 '.'