将String分隔为行时最后一个单词不显示

时间:2015-12-12 00:41:43

标签: php

在$ arrTemp上使用var_dump时,它缺少最后一个单词 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;
    }
}

1 个答案:

答案 0 :(得分:0)

问题是当你到达一个空格时只向automatic添加一个单词,但输入字符串的末尾没有空格。

$arrTemp

DEMO