2015-05-30 50 views

回答

0

试试这个,

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

问题在于它有点矫枉过正。你正在分割字符串,看看你是否有空位。它可以工作,但它使用大锤来驾驶指甲。 – samanime

+0

是的,我同意你的看法,但是OP正在验证这个复选框,IMO我们不需要担心,直到OP在给定时间有10000个访问者,检查[this](http://stackoverflow.com/a/13483548/) 3113793)答案,它说它花了1。738441秒'来执行10000次迭代,我们在这里只需要一个,所以在这里不应该考虑性能。指导我,如果我错了。 – Viral

0

你可以简单地做一个正则表达式测试检查。如果你想阻止的唯一事情是重复的逗号:

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 
} 
0

试试这个:

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

如果我没有弄错,一串“,,”不会被检测为无效。无论OP是在考虑与否的用例都值得怀疑,但它会错过,因为索引将为0,这是不正确的。 – samanime

0

您可以检测到这种使用(会的preg_match工作太当然):

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

您是否还需要检测前导或尾随逗号? 同时请记住,如果确认是不是真的有必要使用explode并过滤掉空字符串元素,你可以简单地“修复”的输入,然后implode数组:

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

使用strpos()功能,为您的上述要求

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

这与样式链接有什么关系? – Cyclonecode

0

可以使用stristr功能来解决这个

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

试试这个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 +。

相关问题