2016-05-31 164 views
1

假设我有一个整数88123401,并且我想确定它是否包含数字序列,如1234,23456,45789或任何长度的数字以及任何数字的开始这在PHP中是否可能呢?如果是这样的话,那么如何才能发现?确定一个字符串是否包含数字序列

+0

您可以使用[正则表达式(http://php.net/book.pcre) – izk

+0

这听起来像一个家庭作业的问题,请你告诉我们你有什么试过吗? –

+0

我曾试着看过子字符串和正则表达式,但我不确定如何去确定这个确切的问题。 –

回答

2

有一些功能让你去通过所有比较其前身每个字符的字符串。

function doesStringContainChain($str, $n_chained_expected) 
{ 
    $chained = 1; 

    for($i=1; $i<strlen($str); $i++) 
    { 
     if($str[$i] == ($str[$i-1] + 1)) 
     { 
      $chained++; 
      if($chained >= $n_chained_expected) 
       return true; 
     }else{ 
      $chained = 1; 
     } 
    } 
    return false; 
} 

doesStringContainChain("6245679",4); //true 
doesStringContainChain("6245679",5); //false 
+1

这几乎就是我希望达到的!非常感谢你!! –

0

将数字视为字符串,然后使用strpos()进行搜索。

例子:

$mystring = '88123401'; 
$findme = '1234'; 
$pos = strpos($mystring, $findme); 


if ($pos === false) { 
    echo "The sequence '$findme' was not found in the number '$mystring'"; 
} else { 
    echo "The sequence '$findme' was found in the number '$mystring'"; 
    echo " and exists at position $pos"; 
} 

来源:http://php.net/manual/en/function.strpos.php

+0

会有更有效的方式去处理所有不同的序列吗? '123','2345','34567'等? –

+0

你可能可以使用一个聪明的正则表达式,但我没有足够的资格来给出最好的答案。 – jtheman

2

使用一个循环,并使用@jtheman

$mystring = '88123401'; 
$findme = array(123,2345,34567); 
foreach ($findme as $findspecificnum) { 
    $pos = strpos($mystring, $findme); 

    if ($pos === false) { 
     echo "The sequence '$findme' was not found in the number '$mystring'"; 
    } else { 
     echo "The sequence '$findme' was found in the number '$mystring'"; 
     echo " and exists at position $pos"; 
    } 
} 

的答案保持它的简单,直接的。

0

这可以帮助你:

$number = "88123401"; 

$splittedNumbers = str_split($number); 
$continuous = false; 
$matches[0] = ''; 
$i = 0; 

do { 
    if ((int)(current($splittedNumbers) + 1) === (int)next($splittedNumbers)) { 
     if($continuous) { 
      $matches[$i] .= current($splittedNumbers); 
     } 
     else { 
      $matches[$i] .= prev($splittedNumbers) . next($splittedNumbers); 
      $continuous = true; 
     } 
    } else { 
     $continuous = false;   
     $matches[++$i] = ''; 
    } 
    prev($splittedNumbers); 
} while (!(next($splittedNumbers) === false)); 

print_r(array_values(array_filter($matches))); 

这列出了所有在数组中的顺序匹配。我们可以根据结果进一步处理。

结果:

Array 
(
    [0] => 1234 
    [1] => 01 
) 
相关问题