Я пытаюсь разделить длинное сообщение на 140 длинных частей. Если часть сообщения не является последней, я хочу добавить 3 точки в конец.PHP - Разделить текст на части 140 символов
У меня возникли проблемы с для цикла ниже - в зависимости от сообщения части длины не хватает, и последнее сообщение получает 3 точки добавлены также:
$length = count($message);
for ($i = 0; $i <= $length; $i++) {
if ($i == $length) {
echo $message[$i];
} else {
echo $message[$i]."...";
}
}
Это полный код:
$themessage = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
function split_to_chunks($to,$text) {
$total_length = (137 - strlen($to));
$text_arr = explode(" ",$text);
$i=0;
$message[0]="";
foreach ($text_arr as $word) {
if (strlen($message[$i] . $word . ' ') <= $total_length) {
if ($text_arr[count($text_arr)-1] == $word) {
$message[$i] .= $word;
} else {
$message[$i] .= $word . ' ';
}
} else {
$i++;
if ($text_arr[count($text_arr)-1] == $word) {
$message[$i] = $word;
} else {
$message[$i] = $word . ' ';
}
}
}
$length = count($message);
for ($i = 0; $i <= $length; $i++) {
if($i == $length) {
echo $message[$i];
} else {
echo $message[$i]."...";
}
}
return $message;
}
if (strlen(utf8_decode($themessage))<141) {
echo "Send";
} else {
split_to_chunks("",$themessage);
}
Что не так с кодом?
попробовать с [chunk_split] (http://php.net/manual/en/function.chunk-split.php) или [str_split] (HTTP : //www.php.net/manual/en/function.str-split.php) – bitWorking
Ваша функция выполняет эхо и возвращает значение. Это правильно? – GolezTrol
Ваш первый цикл превышает границы массива '$ message'. Вместо этого вы должны использовать '$ i <$ length'. – MahanGM