Posted By

jrobinsonc on 06/22/13


Tagged

strings


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

IMPGTX


Cut text to specific length.


 / Published in: PHP
 

Cut text to specific length.

  1. <?php
  2.  
  3. /**
  4.  * Cut text to specific length.
  5.  *
  6.  * @param string $str The text to cut.
  7.  * @param int $limit The maximum number of characters that must be returned.
  8.  * @param stirng $br_char The character to use for breaking the string.
  9.  * @param string $pad The string to use at the end of the cutted string.
  10.  * @return string
  11.  */
  12. function cut_text($str, $limit, $br_char = '', $pad = '...')
  13. {
  14. if (strlen($str) <= $limit) return $str;
  15.  
  16. if ($br_char === '') return substr($str, 0, $limit) . $pad;
  17.  
  18. return substr($str, 0, strrpos(substr($str, 0, $limit), $br_char)) . $pad;
  19. }
  20.  
  21. $text1 = 'Lorem ipsum dolor sit amet, sed do eiusmod tempor incididunt ut laboredo.';
  22.  
  23. // Normal usage:
  24. printf('%s<br>', cut_text($text1, 20));
  25.  
  26. // Using an space for break the string:
  27. printf('%s<br>', cut_text($text1, 20, ' '));

Report this snippet  

You need to login to post a comment.