2016-05-31 2 views
1

정수 88123401이 있고 1234, 23456, 456789 등과 같은 숫자의 시퀀스가 ​​숫자의 시작 부분에 포함되는지 여부를 결정하려고한다고 가정합니다. 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 
) 
관련 문제