我目前正在尝试将一个句子分割成一个字符限制数组。使用explode将句子拆分成单词,如果当前索引的字符串长度小于ie,则将每个单词添加到句子数组中。135.但是我现在对限制有一个问题,我不太确定我做错了什么。任何帮助都将不胜感激。
<?php
function parseDefinition($def){
$tweets = [];
$index = 0;
$wordsArr = explode(" ", $def);
$sentence = "";
$length = 135;
for ($i = 0; $i < count($wordsArr); $i++){
if (!isset($sentences[$index])){
$sentences[$index] = $wordsArr[$i];
}else{
$sentenceLength = strlen($sentences[$index]);
if ($sentenceLength <= $length){
$sentence = $sentences[$index] . " " . $wordsArr[$i];
$sentences[$index] = $sentence;
}else{
$index ++;
$sentence = $wordsArr[$i];
$sentences[$index] = $sentence;
}
}
}
var_dump($sentences);
}
parseDefinition("Vikings follows the adventures of Ragnar Lothbrok, the greatest hero of his age. The series tells the sagas of Ragnar's band of Viking brothers and his family, as he rises to become King of the Viking tribes. As well as being a fearless warrior, Ragnar embodies the Norse traditions of devotion to the gods. Legend has it that he was a direct descendant of Odin, the god of war and warriors.");
?> 发布于 2017-01-28 18:16:37
你只是忘了把你要添加到现有句子中的新单词的大小加进去,然后才决定添加它或开始一个新的句子。
见mods
function parseDefinition($def){
$tweets = [];
$index = 0;
$wordsArr = explode(" ", $def);
$sentence = "";
$length = 135;
for ($i = 0; $i < count($wordsArr); $i++){
if (!isset($sentences[$index])){
$sentences[$index] = $wordsArr[$i];
}else{
// Add the new words size to the calc before adding to sentence
// plus 1 for the space you are also going to add
if (strlen($sentences[$index]) + strlen($wordsArr[$i]) + 1 <= $length){
$sentence = $sentences[$index] . " " . $wordsArr[$i];
$sentences[$index] = $sentence;
}else{
$index ++;
$sentence = $wordsArr[$i];
$sentences[$index] = $sentence;
}
}
}
var_dump($sentences);
}
parseDefinition("Vikings follows the adventures of Ragnar Lothbrok, the greatest hero of his age. The series tells the sagas of Ragnar's band of Viking brothers and his family, as he rises to become King of the Viking tribes. As well as being a fearless warrior, Ragnar embodies the Norse traditions of devotion to the gods. Legend has it that he was a direct descendant of Odin, the god of war and warriors.");结果
array(3) {
[0] =>
string(134) "Vikings follows the adventures of Ragnar Lothbrok, the greatest hero of his age. The series tells the sagas of Ragnar's band of Viking"
[1] =>
string(130) "brothers and his family, as he rises to become King of the Viking tribes. As well as being a fearless warrior, Ragnar embodies the"
[2] =>
string(125) "Norse traditions of devotion to the gods. Legend has it that he was a direct descendant of Odin, the god of war and warriors."
}https://stackoverflow.com/questions/41913026
复制相似问题