【发布时间】:2015-05-30 07:33:45
【问题描述】:
你好,我有一个场景,在文本框中我可以输入类似的字符串
"1,2,3" this would be allowed.
但如果有人进入,
"1,2,,3" this would not be allowed.
允许多个逗号,但不像上面那样。
提前致谢
【问题讨论】:
标签: php regex validation
你好,我有一个场景,在文本框中我可以输入类似的字符串
"1,2,3" this would be allowed.
但如果有人进入,
"1,2,,3" this would not be allowed.
允许多个逗号,但不像上面那样。
提前致谢
【问题讨论】:
标签: php regex validation
试试这个正则表达式:
/^\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
}
【讨论】:
1.738441 seconds 执行 10000 次迭代,我们这里只需要一次,所以这里不应该考虑性能。如果我错了,请指导我。
您可以简单地做一个正则表达式测试来检查。如果您只想防止重复逗号:
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
}
【讨论】:
试试这个:
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';
}
【讨论】: