PHP正则表达式仅用于数字和逗号

use*_*065 7 php regex

我需要创建一个正则表达式来验证逗号分隔的数值.

他们应该看起来像:1,2,3,4,5等......

该值必须是单个数字,如:1之前或之后没有空格,之前或之后没有逗号.

或者......用逗号分隔的多个数值.第一个和最后一个字符必须是数字.

我有以下代码,但它只检查数字和逗号,没有特定的顺序:

如何更改下面的正则表达式以适合上述说明?

谢谢!

// 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;
}
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 35

这应该这样做:

/^\d(?:,\d)*$/
Run Code Online (Sandbox Code Playgroud)

说明:

/            # 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
Run Code Online (Sandbox Code Playgroud)

如果允许多位数字,则更\d改为\d+.