在$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;
}
}
问题是,当你到达一个空格时,你只向$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);
演示