Skip to content

Instantly share code, notes, and snippets.

@Krknv
Created January 19, 2018 04:46
Show Gist options
  • Save Krknv/e6ba8cb131cedc9373741170427b7912 to your computer and use it in GitHub Desktop.
Save Krknv/e6ba8cb131cedc9373741170427b7912 to your computer and use it in GitHub Desktop.
/**
* close all open xhtml tags at the end of the string
*
* @author Milian Wolff <[url]http://milianw.de[/url]>
* @param string $html
* @return string
*/
function closetags($html){
#put all opened tags into an array
preg_match_all("#<([a-z]+)( .*)?(?!/)>#iU",$html,$result);
$openedtags=$result[1];
#put all closed tags into an array
preg_match_all("#</([a-z]+)>#iU",$html,$result);
$closedtags=$result[1];
$len_opened = count($openedtags);
# all tags are closed
if(count($closedtags) == $len_opened){
return $html;
}
$openedtags = array_reverse($openedtags);
# close tags
for($i=0;$i<$len_opened;$i++) {
if (!in_array($openedtags[$i],$closedtags)){
$html .= '</'.$openedtags[$i].'>';
} else {
unset($closedtags[array_search($openedtags[$i],$closedtags)]);
}
}
return $html;
}
// http://forum.dklab.ru/viewtopic.php?p=148338#148338
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment