Created
October 3, 2012 18:11
-
-
Save jo-snips/3828701 to your computer and use it in GitHub Desktop.
Truncate Function For Excerpts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*------------------------------------------------------------------------------- | |
Truncate Function For Excerpts | |
-------------------------------------------------------------------------------*/ | |
function trunc($phrase, $max_words) { | |
$phrase_array = explode(' ',$phrase); | |
if(count($phrase_array) > $max_words && $max_words > 0) { | |
$phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).' … '; | |
} | |
return $phrase; | |
} | |
function restoreTags($input) | |
{ | |
$opened = array(); | |
// loop through opened and closed tags in order | |
if(preg_match_all("/<(\/?[a-z]+)>?/i", $input, $matches)) { | |
foreach($matches[1] as $tag) { | |
if(preg_match("/^[a-z]+$/i", $tag, $regs)) { | |
// a tag has been opened | |
if(strtolower($regs[0]) != 'br') $opened[] = $regs[0]; | |
} elseif(preg_match("/^\/([a-z]+)$/i", $tag, $regs)) { | |
// a tag has been closed | |
unset($opened[array_pop(array_keys($opened, $regs[1]))]); | |
} | |
} | |
} | |
// close tags that are still open | |
if($opened) { | |
$tagstoclose = array_reverse($opened); | |
foreach($tagstoclose as $tag) $input .= "</$tag>"; | |
} | |
return $input; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment