检查范围内的值或不是PHP

时间:2014-05-04 09:03:27

标签: php arrays function output

我想检查范围内的值或不是假设我有范围D1 to D40,如果我输入D20,则返回范围内的值。

我检查了几个解决方案,但这只是整数而不是字符串和整数。

修改

范围将像AA20 to AA30 or like AC10D to AC30D

一样动态

4 个答案:

答案 0 :(得分:5)

你可以写一些更简单的东西......

$arr = range(1,40); //<--- Creating a range of 1 to 40 elements..
array_walk($arr,function (&$v){ $v = 'D'.$v;}); //<--- Concatenating D to all the elements..
echo in_array('D20',$arr) ? 'Found' : 'Not Found'; //<-- The search part.

Demonstration

答案 1 :(得分:2)

首先,您应该从字符串变量中删除字母D,如下所示:

// This is your first variable:
$rang1="D5";

// This is your second rang variable:
$rang2="D20";

$rang1=str_replace("D","",$rang1);
$rang2=str_replace("D","",$rang2);
$rang=$rang2-$rang1;
echo $rang;

或者,如果您的变量如下所示:

$rang="D5 TO D20";

您可以使用以下内容:

$rang="D5 TO D20";
$rang=explode(" TO ",$rang);
$rang1=rang[0];
$rang2=rang[1];

$rang1=str_replace("D","",$rang1);
$rang2=str_replace("D","",$rang2);
$rang=$rang2-$rang1;
echo $rang;

答案 2 :(得分:1)

// 1. build up array of valid entries
$prefix = "D";
$rangeArray = array();
for($i = 1; $i <= 40; $i++) {
    $rangeArray[] = $prefix . $i;
}

...

// 2. check against that array:
$inRange = in_array($needle, $rangeArray); // boolean

获取范围内的位置:

$pos = array_search($needle, $rangeArray); // integer or false if not found

$ needle将是您的输入值。

答案 3 :(得分:1)

以下代码适用于开头不同字母的范围,例如A10B30 (假设A20在此范围内,但A40为不)

$min = "A10";
$max = "B30";
$test = "A20";

$min_ascii = chr($min[0]);
$max_ascii = chr($max[0]);
$test_ascii = chr($max[0]);

$min_number = substr($min, 1);
$max_number = substr($max, 1);
$test_number = substr($test, 1);

if ($min_ascii <= $test_ascii and $test_ascii <= $max_ascii
    and $min_number <= $test_number and $test_number <= $max_number)
{
    echo "$test is in the range from $min to $max";
}