Skip to content

Instantly share code, notes, and snippets.

@Artem-Schander
Last active February 21, 2017 20:00
Show Gist options
  • Save Artem-Schander/444b424177d648df53e08ad9f0fbf029 to your computer and use it in GitHub Desktop.
Save Artem-Schander/444b424177d648df53e08ad9f0fbf029 to your computer and use it in GitHub Desktop.
Close opened HTML tags
<?php
function closetags($html) {
preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
$openedtags = $result[1];
preg_match_all('#</([a-z]+)>#iU', $html, $result);
$closedtags = $result[1];
if (count($closedtags) == count($openedtags)) {
return $html;
}
$openedtags = array_reverse($openedtags);
foreach ($openedtags as $tag) {
if ( ! in_array($tag, $closedtags)) {
$html .= '</'.$tag.'>';
} else {
unset($closedtags[array_search($tag, $closedtags)]);
}
}
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment