I need to create a regular expression to validate comma separated numeric values.
They should look like: 1,2,3,4,5 etc....
The value must be either a single digit like: 1 no empty spaces before or after, no commas before or after.
Or... multiple numerical values separated by commas. First and last characters must be a number.
I have the following code but it only checks for numbers and commas in no particular order:
How can I change the regular expression below to fit the above description?
Thank you!
// get posted value
if(isset($_POST['posted_value']))
{
$sent_value = mysqli_real_escape_string($conn, trim($_POST['posted_value']));
if(preg_match('/^[0-9,]+$/', $posted_value))
{
$what_i_need = $posted_value;
}
else
{
$msg .= $not_what_i_need;
}
}
else
{
$msg .= $posted_value_not_set;
}
The 0-9 indicates characters 0 through 9, the comma , indicates comma, and the semicolon indicates a ; . The closing ] indicates the end of the character set. The plus + indicates that one or more of the "previous item" must be present.
PHP offers two sets of regular expression functions: POSIX Regular Expression. PERL Style Regular Expression.
PHP's Regexp PERL Compatible Functions The preg_match_all() function matches all occurrences of pattern in string. The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
This should do it:
/^\d(?:,\d)*$/
Explanation:
/ # delimiter
^ # match the beginning of the string
\d # match a digit
(?: # open a non-capturing group
, # match a comma
\d # match a digit
) # close the group
* # match the previous group zero or more times
$ # match the end of the string
/ # delimiter
If you allow multi-digit numbers, then change \d
to \d+
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With