This question already has an answer here:
I have a regex
, which is: /[0-9]+(,[0-9]+)*/
.
It accepts only numbers, separated by a comma. For instance:
1,2,3,4 = good
,1,2,3,4 = bad
1,2,3,4, = bad
String = bad
But it also accepts a numbers with a space:
1, 2, 3, 4 = good
How to make regex that wouldn't allow to do so and would only let to enter a numbers, separated by a comma without spaces?
</div>
Your regex is correct as is, you just need to use anchors so you check the full string, and not a partial match.
^[0-9]+(,[0-9]+)*$
https://regex101.com/r/zU22VX/1/
An alternative approach could be:
$string = '1,2,3,4';
$array = str_getcsv($string);
foreach($array as $number) {
if(!is_numeric($number)) {
echo 'Bad value' . $number;
break;
}
}
This should work:
/^\d(,\d)*$/
^
match the beginning of the string\d
match a digit$
match the end of the stringExample:
if (preg_match("/^\d(,\d)*$/", $string))
echo "good";
else
echo "bad";
Use this:
^(\d,(?=\d))*\d$
How it works:
^
: match strings which starts with..(what follows)(...)*
: what inside the brackets can be repeated any number of times\d,(?=\d)
: this is the block that is allowed to repeat. It looks for a number from 0 to 9 followed by a comma which is followed by a number. The number following the comma is not included in the match.\d$
: finally, the string must terminate with a number.