-1

Is there a way to check if D30500 is within D000000 - D300000 range using regular expression. If not what would be the easiest way ?

Update

Sorry for not mentioning in the beginning. Range can be like ASD000 - ASD3000 and check if ASD1000 is within the range, CH0000 - CH50000 and check if CH250 is within the range. So, any number of alphabetic characters can be there at the beginning and I was wondering if there is direct regex comparison to check a given code is withing the range without splitting the strings.

Shaolin
  • 2,541
  • 4
  • 30
  • 41

3 Answers3

1

1) AS stated in the comments I would use the magic of math

 if(preg_match( '/^D([0-9]+)/', 'D30500', $match )){
     if( $match[1] < 300000 ){  //$match[1] = '30500';
        //do something
     } 
 }

For the Regx https://regex101.com/r/KppvPh/1

2) You could also just do substr too

 $number = substr('D30500', 1 ); //= 30500

Such as this

   $check = substr("D30500" ,1);
   $start = substr("D000000" ,1);
   $end =  substr("D300000" ,1);

  if( $check > $start && $check < $end ){
         //bla bla ( inclusive? )
  }

And if you want to get real fancy you can cast it as an int $start = intval(substr("D000000" ,1));

3) You cal also do that using array.

<?php
    $from = 'D101';
    $to = 'D105';

    array_walk(range(substr($from,1),substr($to,1)), function ($v, $k) {
        $search = 'D105';
        if($v==substr($search,1)){
            echo "Yes !!!";
        } 
    });
?>

4) Updated answer.

<?php
    // 2)
    $from = 'ASD000';
    $to = 'ASD3000';
    $search = 'ASD3000';

    preg_match_all('!\d+!', $from, $matches);
    $from_int = $matches[0][0];
    preg_match_all('!\d+!', $to, $matches);
    $to_int = $matches[0][0];
    preg_match_all('!\d+!', $search, $matches);
    $search_int = $matches[0][0];

    if( $search_int > $from_int && $search_int < $to_int ){
        echo "Yes !!!";
    }
?>
Jaydeep Mor
  • 1,690
  • 3
  • 21
  • 39
ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
0

Try this one..

preg_match('/[A-z]([\d]+)/', "DBB30500" ,$matches1);
preg_match('/[A-z]([\d]+)/', "DXXX000000" ,$matches2);
preg_match('/[A-z]([\d]+)/', "DCHDH300000" ,$matches3);

if(!empty($matches1)){
   $numberToCheck = $matches1[1];
   $numberFirstParameter = $matches2[1];
   $numberSecondParameter = $matches3[1];
   if($numberToCheck >= $numberFirstParameter && $numberToCheck <= $numberSecondParameter){
      echo $numberToCheck.' is within '.$numberFirstParameter.' and '.$numberSecondParameter;
   }
}
aswzen
  • 1,512
  • 29
  • 46
0

try this if it does not specify the alphabet

  • for range 0-300000 : ^[A-z]*([0-3][\d]{0,5})$ fiddle

  • for range 0-2000: ^[A-z]*([0-2][\d]{0,3})$

If you specifies the alphabet

  • for 'CH' range 0-300000: ^CH([0-3][\d]{0,5})$ fiddle
Arya Putra
  • 91
  • 2
  • 8