PHP: Truncate a string at a word break


/ Published in: PHP
Save to your folder(s)

Truncates the given string at the specified length.


Copy this code and paste it in your HTML
  1. /**
  2.  * Truncates the given string at the specified length.
  3.  *
  4.  * @param string $str The input string.
  5.  * @param int $width The number of chars at which the string will be truncated.
  6.  * @return string
  7.  */
  8. function truncate($str, $width) {
  9. return current(explode("\n", wordwrap($str, $width, "...\n")));
  10. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.