1
我正在嘗試將句子拆分爲字符受限陣列。如果當前索引的字符串長度小於ie,則使用explode
將句子拆分爲單詞,然後將每個單詞添加到句子數組中。 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.");
?>
請詳細解釋問題所在。是否句數最後超過135個字符 – RiggsFolly
@RiggsFolly是數組中的字符串長度超過了指定的長度 – kye
所以一個句子必須是135個字符還是不對? – RiggsFolly