开发者

PHP check ascending/descending digits

开发者 https://www.devze.com 2023-02-02 23:41 出处:网络
I am writing a PHP script. I n开发者_StackOverfloweed to make sure that part of a string is ascending/descending.

I am writing a PHP script. I n开发者_StackOverfloweed to make sure that part of a string is ascending/descending.

Example:

$var = "0212345";

$var2 = "0254321";

How can I write the if condition to check whether the last 5 digits are in ascending or descending sequence?


If you want the 5 digits to be consecutive numbers (which appears to be the case from a comment on a deleted answer), then you can use strpos():

$ascending  = strpos("0123456789", str_split($var, -5)) !== false;
$descending = strpos("9876543210", str_split($var, -5)) !== false;

If you want the 5 digits to be in increasing/decreasing order (but not necessarily consecutive), you can use a regular expression:

(?=\d{5})(0*1*2*3*4*5*6*7*8*9*|9*8*7*6*5*4*3*2*1*0*)$

?=\d{5} is a positive lookahead and makes sure we're matching 5 digits. Combined with the $ at the end, this matches the last 5. Then the sequence of ascending/descending digits checks that the digits we're matching are in either ascending or descending order. If you need to know which of the two it is, then split it up into two separate regular expressions.

0

精彩评论

暂无评论...
验证码 换一张
取 消