¿Eres nuevo? ¡Lee el FAQ y ponte al día!
813 visitas

Truncate string to certain length without cutting the final word in half

This function takes a long string and shortens it to a defined length and adds appends an ellipsis (or custom string) to the end. Instead of chopping a word in half (if the limit finished within it), it moves the pointer up to the previous space.

PHP
  1. /**
  2.  * Truncates a string to a certain length
  3.  * @param string $text
  4.  * @param int $limit
  5.  * @param string $ending
  6.  * @return string
  7.  */
  8. function truncate($text, $limit = 25, $ending = '...') {
  9.     if (strlen($text) > $limit) {
  10.         $text = strip_tags($text);
  11.         $text = substr($text, 0, $limit);
  12.         $text = substr($text, 0, -(strlen(strrchr($text, ' '))));
  13.         $text = $text . $ending;
  14.     }
  15.  
  16.     return $text;
  17. }
  18.  

­

Found here

Etiquetas: PHP strings truncate

Insertar: