Home » Php » regex – PHP regular expression for numbers and commas only

regex – PHP regular expression for numbers and commas only

Posted by: admin July 12, 2020 Leave a comment

Questions:

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;
}
How to&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+.

Answer:

Do you allow the user to input numbers with commas in them, like 5,000 for example? what about decimals like 5.6?

Alternatively you could validate the input using explode something like this.

$values = explode(',',$sent_value);
$valid = true;

foreach($values as $value) {
    if(!ctype_digit($value)) {
        $valid = false;
        break;
    }
}