简体   繁体   English

检查范围内的值或不是PHP

[英]Check value within range or not php

I want to check value with in range or not suppose if I have range D1 to D40 and if I enter D20 then it returns value with in range. 我想检查范围内的值或不是假设我有D1 to D40范围,如果我输入D20那么它返回范围内的值。

I check several solution but this are for only integer not for both string and integer. 我检查了几个解决方案但这只是整数而不是字符串和整数。

EDIT 编辑

Range will be dynamic like AA20 to AA30 or like AC10D to AC30D 范围将是动态的,如AA20 to AA30 or like AC10D to AC30D

You can write something simpler like this... 你可以写一些更简单的东西......

$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 示范

First, you should remove the letter D from your string variable, like this: 首先,您应该从字符串变量中删除字母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;

Or if your variable looks like this: 或者,如果您的变量如下所示:

$rang="D5 TO D20";

you can use the following: 你可以使用以下内容:

$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;
// 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

To get the position in the range: 要获得该范围内的位置:

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

Where $needle would be your input value. $ needle将是您的输入值。

The following code will work with ranges with different letter in the beginning like A10 to B30 (assuming A20 is in that range, but A40 is not) : 以下代码将使用开头不同字母的范围,如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";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM