首页 > 解决方案 > 如何验证一串数字和逗号,但不是字母字符

问题描述

如何编写用于 PHP (preg_match) 的正则表达式来仅验证数字和逗号(可选)?我想出了这个:

[,0-9]+

但它似乎不起作用。这就是我想要实现的目标:

1 -> OK
1,2 -> OK
1,2,3 -> OK
abc -> NO
1,a -> NO
1,2,a -> NO
1, a, 2 -> NO

标签: phpregex

解决方案


试试这个:^[,0-9]+$

演示

代码:

$re = '/^[,0-9]+$/m';
$str = '1
1,2
1,2,3
abc
1,a
1,2,a
1, a, 2
';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

推荐阅读