我希望在PHP验证中两个字母之间只允许有一个逗号


I wanted to allow only 1 comma between 2 letters in PHP validation

你好,我有一个场景,在文本框中我可以输入像

这样的字符串
"1,2,3" this would be allowed.

但如果有人进入,

"1,2,,3" this would not be allowed.

允许多个逗号,但不像上面那样。

Thanks in advance

试试这个reg-ex:

/^'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+。

试试这个,

if(in_array("", explode(',',$str)))
{
    // validation fail
}

您可以简单地做一个正则表达式测试来检查。如果您唯一想要防止的是重复的逗号:

if (preg_match('/,,/', $myString)) {
    // not allowed... do something about it
}

如果您希望将其限制为只有一个以逗号分隔的数字模式,请将正则表达式模式交换为'/^([0-9]+,?)+$/',该模式只有1个或多个数字,可选地后跟一个小数,并且该模式重复任何次数(但必须至少有一个数字)。同时,将条件翻转过来,因此:

if (!preg_match('/^([0-9]+,?)+$/', $myString)) {
    // not allowed... do something about it
}

如果你想要一些更简单的东西,这样做也会解决它(并且更有效,如果你只想测试多个逗号在一起):

if (strpos($myString, ',,') !== false) {
    // not allowed... do something about it
}

Try This:

if (strpos($input_string,',,') == true) {
    echo 'Invalid string';
}

您可以使用(preg_match当然也可以):

if(strpos($your_string, ',,') !== false) {
   echo "Invalid"
}

还需要检测逗号的前导或尾随吗?还要记住,如果验证不是真正必要的,你可以简单地"修复"输入使用explode和过滤掉空字符串元素,然后implode数组:

$your_string = implode(',', array_filter(explode(',', $your_string), function ($i) {
    return $i !== '';
}));

您可以使用stristr函数来修复这个

if(stristr ($Array,',,'))
echo 'Flase';
else
// do something

使用strpos()函数满足您的上述需求

 if (strpos($youstring,',,') == false) {
        echo 'String not found';
    }
    else
    {
        echo 'String is found';
    }