2014-01-09 50 views
1

我有一些像例如4,3或5的值。preg_match數字和逗號

我想只允許數字(從0到9)和逗號。

我發現這個函數,pregmatch但它不能正常工作。

<?php 
$regex="/[0-9,]/"; 
if(!preg_match($regex, $item['qty'])){ 
// my work 
} 
?> 

怎麼了? 感謝

回答

6

更正語法:

$regex="/^[0-9,]+$/"; 

^表示線的開始

+表示字符組的一個或多個

$表示行結束

+0

^[0 -9] +,[0-9,] + $ – YumYumYum

+0

應該在2,3, – Bingy

3

這應做到:

'~^\d+(,\d+)?$~'

它允許例如111,5但未能上1,,,1,,

  • ^開始的
  • \d+後面跟着一個或多個數字
  • (,\d+)?可選:逗號,後面跟着一個或多個數字
  • $結束

\d是數字[0-9]

一個shorthand你問這有什麼錯$regex="/[0-9,]/";

這將匹配任何0-9,這是在[characterclass]。甚至當匹配像abc1sa,b這樣的字符串時,因爲沒有anchors被使用。

+0

不錯,但嘗試 '〜^ \ d +(\ d +)* $〜',使其符合兩個以上的值 – Bingy

0
<?php 
    $regex = '/^[0-9,]+$/'; 
    if(!preg_match($regex, $item['qty'])) { 
     // my work 
    } 
?> 
1

如果喲你知道這將是一個逗號分隔的列表,然後使用explode()

<?php 

// test item with incorrect entries 
$item = '1,2,3,4,d,@,;'; 

// explode whatever is between commas into an array 
$item_array = explode(',', $item); 

// loop through the array (you could also use array_walk()) 
foreach($item_array as $key => $val) 
{ 
    // to clean it 
    $item_array[$key] = (int) $val; 

    // use the values here 
} 

// or here 
?>