Advertisement
jonahcoyote

Custom PHP Truncate Function

Jan 19th, 2012
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.28 KB | None | 0 0
  1. /*-------------------------------------------------------------------------------
  2.     Truncate Function For Excerpts
  3. -------------------------------------------------------------------------------*/
  4. function trunc($phrase, $max_words) {
  5.    $phrase_array = explode(' ',$phrase);
  6.    if(count($phrase_array) > $max_words && $max_words > 0) {
  7.       $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).' … ';
  8.    }
  9.    return $phrase;
  10. }
  11.  
  12.  
  13.   // Original PHP code by Chirp Internet: www.chirp.com.au
  14.   // Please acknowledge use of this code by including this header.
  15.  
  16. function restoreTags($input)
  17. {
  18.   $opened = array();
  19.  
  20.   // loop through opened and closed tags in order
  21.   if(preg_match_all("/<(\/?[a-z]+)>?/i", $input, $matches)) {
  22.     foreach($matches[1] as $tag) {
  23.       if(preg_match("/^[a-z]+$/i", $tag, $regs)) {
  24.         // a tag has been opened
  25.         if(strtolower($regs[0]) != 'br') $opened[] = $regs[0];
  26.       } elseif(preg_match("/^\/([a-z]+)$/i", $tag, $regs)) {
  27.         // a tag has been closed
  28.         unset($opened[array_pop(array_keys($opened, $regs[1]))]);
  29.       }
  30.     }
  31.   }
  32.  
  33.   // close tags that are still open
  34.   if($opened) {
  35.     $tagstoclose = array_reverse($opened);
  36.     foreach($tagstoclose as $tag) $input .= "</$tag>";
  37.   }
  38.  
  39.   return $input;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement