Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regular expression for numbers and commas only

Tags:

regex

php

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;
}
like image 467
user582065 Avatar asked Nov 07 '11 01:11

user582065


People also ask

How do you use commas in regex?

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.

How many types of regular expression are available in PHP?

PHP offers two sets of regular expression functions: POSIX Regular Expression. PERL Style Regular Expression.

Are there regular expressions in PHP?

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.


1 Answers

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+.

like image 122
Felix Kling Avatar answered Oct 15 '22 02:10

Felix Kling