Skip to content

Instantly share code, notes, and snippets.

@Artem-Schander
Created February 21, 2017 19:59
Show Gist options
  • Save Artem-Schander/d71f0ed41a9844cbcadf8b6025441e65 to your computer and use it in GitHub Desktop.
Save Artem-Schander/d71f0ed41a9844cbcadf8b6025441e65 to your computer and use it in GitHub Desktop.
Open closed HTML tags
<?php
function opentags($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];
$len_closed = count($closedtags);
if (count($openedtags) == $len_closed) {
return $html;
}
$tags = '';
$openedtags_occurences = array_count_values($openedtags);
$closedtags_occurences = array_count_values($closedtags);
$closedtags = array_reverse($closedtags);
foreach ($closedtags as $tag) {
if (isset($openedtags_occurences[$tag]) && $openedtags_occurences[$tag] < $closedtags_occurences[$tag]) {
$tags.= '<'.$tag.'>';
++ $openedtags_occurences[$tag];
} elseif ( ! isset($openedtags_occurences[$tag])) {
$tags.= '<'.$tag.'>';
$openedtags_occurences[$tag] = 1;
}
}
return $tags.$html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment