2011-11-07 648 views
5

我需要创建一个正则表达式验证逗号分隔的数值。数字和逗号PHP正则表达式只

他们应该是这样的:1,2,3,4,5等....

的值必须是一个数字,如:1点之前或之后没有空的空间,没有逗号之前或之后。

或者......多个数值以逗号分隔。第一个和最后一个字符必须是一个数字。

我有以下的代码,但它仅检查数字和逗号没有特定的顺序:

如何更改下面的正则表达式符合上面的描述?

谢谢!

// get posted value 
if(isset($_POST['posted_value'])) 
{ 
    $sent_value = mysqli_real_escape_string($conn, trim($_POST['posted_value'])); 
    if(preg_match('/^[0-9,]+$/', $posted_value)) 
    { 
     $what_i_need = $posted_value; 
    } 
    else 
    { 
     $msg .= $not_what_i_need; 
    } 
} 
else 
{ 
    $msg .= $posted_value_not_set; 
} 
+0

只是为了说明编辑的原因,当你的意思是[this](http://en.wikipedia.org/wiki/Coma)时,你说的是[this](http://en.wikipedia.org/wiki/Coma) .ORG /维基/逗号)。 – darvids0n

回答

28

这应做到:

/^\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+

2

你允许用户输入数字与他们逗号,像5,000例如?小数点如5.6怎么样?

或者,您也可以验证使用爆炸这样的事情的投入。

$values = explode(',',$sent_value); 
$valid = true; 

foreach($values as $value) { 
    if(!ctype_digit($value)) { 
     $valid = false; 
     break; 
    } 
}