Skip to content

Instantly share code, notes, and snippets.

@wonjun27
Created February 11, 2015 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wonjun27/86e1c19948d28953e180 to your computer and use it in GitHub Desktop.
Save wonjun27/86e1c19948d28953e180 to your computer and use it in GitHub Desktop.
<?PHP
// Found on http://www.the-art-of-web.com/php/truncate/
// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
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