2015-05-30 52 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 +。

相關問題