2013-07-29 3 views
2

Я пытаюсь разделить длинное сообщение на 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); 
} 

Что не так с кодом?

+0

попробовать с [chunk_split] (http://php.net/manual/en/function.chunk-split.php) или [str_split] (HTTP : //www.php.net/manual/en/function.str-split.php) – bitWorking

+0

Ваша функция выполняет эхо и возвращает значение. Это правильно? – GolezTrol

+0

Ваш первый цикл превышает границы массива '$ message'. Вместо этого вы должны использовать '$ i <$ length'. – MahanGM

ответ

2

попробовать с chunk_split

echo substr(chunk_split($themessage, 137, '...'), 0, -3); 

Чтобы сохранить полные слова просто использовать wordwrap

echo wordwrap($themessage, 137, '...'); 
0

Использование array_slice, если есть более 140 клавиш, в противном случае печать, как это было

<?php 
$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."; 
$words = explode(' ', $themessage); 

if (count($words) > 140) 
{ 
    echo implode(' ', array_slice($words, 0, 140)) . '...'; 
} 
else 
{ 
    echo $themessage; 
} 
?> 

Если вы не хотели 140 символов, а не слова - ваш пример не определяя, что ясно, но ваш код дает два варианта. Для этого:

<?php 
$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."; 
if (strlen($themessage) > 140) 
{ 
    echo preg_replace('/\s*[^\s]+$/', '...', substr($themessage, 0, 137)); 
} 
else 
{ 
    echo $themessage; 
} 
?> 
-1

Как насчет рекурсии?

/** 
* Split a string into chunks 
* @return array(part, part, part, ...) The chunks of the message in an array 
*/ 
function split_to_chunks($str) { 
    // we're done 
    if (strlen($str) <= 140) 
    return array($str); 

    // otherwise recur by merging the first part with the result of the recursion 
    return array_merge(array(substr($str, 0, 137). "..."), 
        split_to_chunks(substr($str, 137))); 
} 

Если вы хотите разделить границы слов, найдите индекс последнего символа пробела в куске.

// splits on word boundaries 
function split_to_chunks($str) { 
    // we're done 
    if (strlen($str) <= 140) 
    return array($str); 

    $index = strrpos(substr($str, 0, 137), " "); 
    if (!$index) $index = 137; 
    return array_merge(array(substr($str, 0, $index). "..."), 
        split_to_chunks(substr($str, $index))); 
} 
+0

Рекурсивный вызов для разбора строки неизвестной длины является неэффективным и рискованным, не говоря уже о необходимости. – GolezTrol

+0

Рекурсия - плохая идея для случайных строк длины - ее просьба о утечке памяти – exussum

+0

@GolezTrol - укажите, КАК это утечка памяти. Также имейте в виду, что решение является лишь частью проблемы. Вопрос заключался не в том, как иметь дело со строками случайной длины. Что касается нерегулярности рекурсии, я сильно не согласен - рекурсия предлагает элегантный и простой способ решить эту проблему. –

0

Использование str_split. Он позволяет передавать строку и длину и возвращает массив частей.

Энди прав, что вам нужно немного больше кода для решения последнего вопроса. То есть, если вы хотите сделать это действительно приятно. Многие фрагменты кода просто разделили строку на 137 символов и добавили «...» после каждого из них, даже если последний фрагмент длиной 1, 2 или 3 символа, поэтому его можно было бы объединить со следующим последним.

Во всяком случае, вот код:

<?php 
function chunkify($str, $chunkSize, $postfix) 
{ 
    $postfixLength = strlen($postfix); 
    $chunks = str_split($str, $chunkSize - $postfixLength); 
    $lastChunk = count($chunks) - 1; 
    if ($lastChunk > 0 && strlen($chunks[$lastChunk] <= $postfixLength)) 
    { 
    $chunks[--$lastChunk] .= array_pop($chunks); 
    } 

    for ($i = 0; $i < $lastChunk; $i++) 
    { 
    $chunks[$i] .= '...'; 
    } 

    return $chunks; 
} 

var_dump(
    chunkify(
    'abcdefghijklmnopqrstuvwxyz', 
    6, // Make this 140. 
    '...')); 
+0

не решает проблему расщепления на нерегулярные фигуры - 137 символов или меньше, последнее может быть до 140 –

+0

@ AndyJones использует printf или sprintf для обработки str_spilt - лучшее решение здесь до сих пор IMO – exussum

+0

аргумент sprintf '% '.- 140s ' – exussum

Смежные вопросы