Skip to content

Instantly share code, notes, and snippets.

@pedrosancao
Created September 1, 2015 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedrosancao/903be116ab8be7fbdd2f to your computer and use it in GitHub Desktop.
Save pedrosancao/903be116ab8be7fbdd2f to your computer and use it in GitHub Desktop.
<?php
/**
* Close open HTML tags and get the ones left open
*
* @author Pedro Sanção <pedro at sancao do co>
* @license MIT Licence
*
* @param string $html
* @return array tags without closing pair
*/
function closeOpenTags(&$html) {
$indexes = array();
$matches = array();
preg_match_all('#<(/?)([a-z0-9]+).*?(/?)>#m', $html, $matches);
$tagNames = $matches[2];
$limit = count($matches[0]);
for ($k = 0; $k < $limit; $k++) {
if (!empty($matches[3][$k])) { // self closing tags
} elseif (empty($matches[1][$k])) { // tag open
array_push($indexes, $k);
} elseif ($tagNames[$k] === $tagNames[end($indexes)]) { // tag closed
array_pop($indexes);
} else { // malformed HTML
}
}
if (!empty($indexes)) {
$indexes = array_flip($indexes);
$tags = array_intersect_key($tagNames, $indexes);
foreach ($tags as &$tag) {
$tag = sprintf('</%s>', $tag);
}
$html = trim($html) . join(array_reverse($tags));
return array_intersect_key($matches[0], $indexes);
}
return array();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment