php - How to validate a string of numbers and commas, but not alpha chars

How can I write a regex to be used in PHP (preg_match) to only validate numbers and commas (optionally)? I come up with this:
[,0-9]+
but it doesn't seem to work. this is what I am trying to achieve:
1 -> OK
1,2 -> OK
1,2,3 -> OK
abc -> NO
1,a -> NO
1,2,a -> NO
1, a, 2 -> NO
Answer
Solution:
try this:^[,0-9]+$
See Demo
Code:
$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);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: deprecated: directive 'allow_url_include' is deprecated in unknown on line 0
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.