gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 12:40:38 25 4
gpt4 key购买 nike

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

它们应该看起来像: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;
}

最佳答案

应该这样做:

/^\d(?:,\d)*$/

解释:

/            # 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

如果您允许多位数,则将 \d 更改为 \d+

关于仅用于数字和逗号的 PHP 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8031779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com