2015-12-12 39 views
0

在使用上的var_dump $ arrTemp它缺少硬道理 http://phptester.net最後一個字不顯示

我看不到什麼是錯的,我是一個新手

此代碼是一個字符串分隔成線,如果達到20個字符

$arrMessage = str_split(stripcslashes("test asdasd")); 
$arrTemp = array(); 
$line = 0; 
$word = array(); 
$arrTemp[$line] = array(); 

foreach($arrMessage as $char) { 

    if($char == " ") { 
     //calculate numbers of chars currently on line + number of chars in word 
     $numTotalChars = count($word) + (int) count($arrTemp[$line]); 
     //if total > 20 chars on a line, create new line 
     if($numTotalChars > 20) { 
      $line++; 
      $arrTemp[$line] = array(); 
     } 
     $word[] = $char; 
     //push word-array onto line + empty word array 
     $arrTemp[$line] = array_merge($arrTemp[$line], $word); 
     $word = array(); 
    } else { 
     //if word is too long for a line, split it 
     if(count($word) > 20) { 
      $numTotalChars = (int) count($word) + (int) count($arrTemp[$line]); 

      if($numTotalChars > 20) { 
       $line++; 
       $arrTemp[$line] = array(); 
      } 

      $arrTemp[$line] = array_merge($arrTemp[$line], $word); 
      $word = array(); 
     } 
     $word[] = $char; 
    } 
} 
+0

請忽略此COMMENT:str_split(stripcslashes( 「阿德asdasd」));.你有一個錯字,它必須是str_split(stripslashes(「adriano asdasd」));.你有一個這樣的錯誤調試器。 – Franco

+0

@Barmar哇!我很久沒有使用這個功能了。我不再依賴這些功能。無論如何,感謝指向我的臨時工? – Franco

+1

只是刪除你的評論,而不是添加「IGNORE THIS」 – Barmar

回答

0

的問題是,你只添加一個詞來$arrTemp當你到一個空間,但有輸入字符串的結尾沒有空格。

<?php 
$arrMessage = str_split(stripcslashes("adriano asdasd")); 
$arrTemp = array(); 
$line = 0; 
$word = array(); 
$arrTemp[$line] = array(); 

foreach($arrMessage as $char) { 

    if($char == " ") { 
     //calculate numbers of chars currently on line + number of chars in word 
     $numTotalChars = count($word) + count($arrTemp[$line]); 
     //if total > 20 chars on a line, create new line 
     if($numTotalChars > 20) { 
      $line++; 
      $arrTemp[$line] = array(); 
     } 
     $word[] = $char; 
     //push word-array onto line + empty word array 
     $arrTemp[$line] = array_merge($arrTemp[$line], $word); 
     $word = array(); 
    } else { 
     //if word is too long for a line, split it 
     if(count($word) > 20) { 
      $numTotalChars = count($word) + count($arrTemp[$line]); 

      if($numTotalChars > 20) { 
       $line++; 
       $arrTemp[$line] = array(); 
      } 

      $arrTemp[$line] = array_merge($arrTemp[$line], $word); 
      $word = array(); 
     } 
     $word[] = $char; 
    } 
} 
// Add last word if there's something left over 
if (count($word)) { 
    $numTotalChars = count($word) + count($arrTemp[$line]); 
    if ($numTotalChars > 20) { 
     $line++; 
     $arrTemp[$line] = array(); 
    } 
    //push word-array onto line + empty word array 
    $arrTemp[$line] = array_merge($arrTemp[$line], $word); 
} 
var_dump($arrTemp); 

DEMO

+0

現在最後一個字符被複制 – Skelun

+0

我已經修復了這個問題。 – Barmar