我想创建一个用户可以查看奖金数字的网站,我也知道一些关于PHP的内容,所以我在html中创建了一个表单:
<form>
Enter your price bond number <input type="text" name="number"><br>
<input type="submit" value="try your luck">
</form>
现在在php中,我想检查它是单个数字,范围数字还是以逗号分隔的数字,例如:
1023342
1023342-10233100
1023342,1023343,1023344,1023345
我想根据用户输入的内容采取不同的行动。
答案 0 :(得分:1)
$mynumber = $_POST["number"];
$pieces = explode(",", $mynumber);
if(count($pieces)>0)
echo "Comma separated";
$pieces = explode("-", $mynumber);
if(count($pieces)>0)
echo "Range Value";
else
echo "Single Value";
上面的代码在某种程度上很有用,最后你将有一组数字要处理。
答案 1 :(得分:0)
您可以使用
strpos
像这样
if (strpos($str,',') == true) {
echo "it has comma";
} else if (strpos($str,'-') == true) {
echo "it has hyphen";
} else {
echo "single number";
}
通过替换echo将您的各自功能置于if条件中。
答案 2 :(得分:0)
做这样的事情:
<?php
$value=1023342;
if (preg_match("-", $value)) {
echo " - was found.";
} else if(preg_match(",", $value)){
echo " , was found";
}
else
{
echo "it is a simple number";
}
?>
答案 3 :(得分:0)
function check_input($number){
if(ctype_digit($number)){
//case1: simple number
return 1;
}
if(preg_match('/(\d)-(\d)/', $number, $out)){
//Case2: range
//we need to check if the range is valid or not
if($out[1] >= $out[2]){
//echo 'error: the first number in range should be lessthan second number';
return false;
}
return 2;
}
if(preg_match('/\d+(,\d+)+/', $number, $out)){
//Case3: comma seperated
return 3;
}
return false;
}
//usage
if(check_input($number) == 1){
//do something
}
答案 4 :(得分:0)
考虑到用户可能会提交输入内容,我觉得所有其他答案都有点不足。我决定编写一个全面的解决方案,它将删除无效值并生成一系列有效值,以便继续处理。
代码:(PHP Demo&amp; Regex Pattern Demo/Explanation)
// declare limit that value ranges cannot exceed (for project-specific reasons
// and/or to avoid memory limitation failures)
$limit=100;
$result=[]; // declare an empty array
// split on commas, and filter out any invalid values
foreach(preg_grep("/^( ?(\d+-\d++|\d+),?)+$/",explode(',',$input)) as $chunk){
if(strpos($chunk,'-')===false){
$result[]=(int)$chunk; // cast value as an integer for uniformity
}else{
$range=explode('-',$chunk);
if(($size=abs($range[0]-$range[1]))<=$limit){
$result=array_merge($result,range($range[0],$range[1]));
}else{
echo "Value range ($range[0] to $range[1]) size ($size)
exceeds allowed limit ($limit)";
}
}
}
运行此代码块后,您可以根据项目的需要使用$result
数组中的值。
我的代码将允许用户:
我的代码会过滤掉: