2016-05-31 183 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 
) 
相關問題