Code SnippetsString Truncate Syndicate content

Wed, 07/19/2006 - 14:26

If you write a CMS you will have to truncate your contents to automagically create summaries. The following function will do the job:

If you write a given string (default '<!--MORE-->') inside one of your contents, the text will be truncated to that position.

Else the function looks for the nearest word boundary after at least $len characters and cuts there. Because that might be directly inside your text $append will be appended. To prevent that the markup is messed up, closetags() is called.

  1. /**
  2.  * if $splitter is found inside the $str, everything before $splitter will be
  3.  * returned.
  4.  * else truncates $str after $length chars (actually at the nearest
  5.  * word boundary after at least $len characters). Also $append will be added to
  6.  * $str
  7.  *
  8.  * @param string &$str
  9.  * @param integer $length
  10.  * @param optional string $hardbreak
  11.  * @param optional string $append
  12.  * @return string
  13.  * @author Milian Wolff <mail@milianw.de>
  14.  */
  15. function truncate($str, $len = 200, $splitter = '<!--MORE-->', $append = '…') {
  16. if (strlen($str) <= $len) {
  17. return $str;
  18. }
  19. if ($len > 0 && !strstr($str, $splitter)) {
  20. preg_match('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){'.$len.',}\b#U', $str, $matches);
  21. $str = $matches[0];
  22. # remove trailing opener tags and close all other open tags:
  23. $str = closetags(preg_replace('#\s*<[^>]+>?\s*$#', '', $str).$append);
  24. } else {
  25. $arr = explode($splitter, $str, 2);
  26. $str = $arr[0];
  27. }
  28. return $str;
  29. }

Comments

Post new comment

  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <pre>.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options