2014-09-02 55 views
-2

我有這個代碼,由於某種原因,它保留在一個無限循環,當它假設只是打印所有可能的子字符串。這是完整功能的一部分。該函數的目的是從字符串$ str1中找到的字符串$ str2返回子字符串的索引。非常感謝您的幫助。PHP substring找到無限循環錯誤

$str1='QYDIKYTWNVPKIAPKS'; 
$str2='KYTWNVPKSS'; 
print($str1);echo"</br>";print($str2);echo"</br>"; 
function overlapping($str1,$str2) { 
    $peptide1 = str_split($str1); 
    $peptide2 = str_split($str2); 
    $longest_seq=array(); 
    $len=count($peptide2)-1; 
    for ($i = 0; $i < count($peptide1); ++$i) { 
     for ($j = 0; $j < count($peptide2); ++$j) { 
      if ($peptide2[$j]==$peptide1[$i]){ 
       $k=$j; 
       $start=$j; 
       $l=$i; 
       $tmp=array(); 
       while ($peptide2[$k]==$peptide1[$l]){ 
        array_push($tmp, $peptide2[$k]); 
        $substring=implode($tmp); 
         print $substring; 
         echo"</br>"; 
        $k=$k+1; 
        $l=$l+1; 
       } 
      } 
     } 
    } 
} 

也許你有如何提取匹配的子指數另一個想法,我也可以嘗試

+0

@丹,抱歉,不,他正在推動$ tmp的聲明。 $肽2保持不變。 – CarCzar 2014-09-02 17:53:19

+0

array_push($ tmp,$ peptide2 [$ k]);增加$ tmp數組的長度,而不是$ peptide2數組。當我在$ str2的末尾使用相同的字符時,問題就來了。如果我用$ str2測試它作爲$ str1的完美子字符串,那麼它工作得很完美。但是當我在開始或結束脩改$ str2時,它不起作用 – 2014-09-02 17:55:36

回答

0

你從來沒有檢查,以確保$ k和$ L是有效的偏移。檢查在這裏:的

while (isset($peptide2[$k]) && isset($peptide1[$l]) && $peptide2[$k]==$peptide1[$l]){ 

代替

while ($peptide2[$k]==$peptide1[$l]){ 
+0

謝謝!有效 – 2014-09-02 18:04:39

0

我不知道這有什麼用您的問題,但在我的for循環中,我總是後遞增。

for ($i = 0; $i < count($peptide1); $i++) { 
     // do stuff 
    }