Created
September 17, 2015 20:35
-
-
Save sQu1rr/0a2006e146b274433441 to your computer and use it in GitHub Desktop.
Snippet that closes unclosed HTML tags in HTML extract (useful when HTML string is trimmed by some specific length)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function closeCutoff($text) | |
{ | |
static $closing = [ | |
'img', 'br', 'input', 'hr', 'area', 'base', 'basefont', 'col', | |
'frame', 'isindex', 'link', 'meta', 'param' | |
]; | |
$skip = []; | |
$add = []; | |
preg_match_all('/<\s*(\/?)\s*(\w+)/i', $text, $matches, PREG_SET_ORDER); | |
foreach (array_reverse($matches) as list($full, $close, $tag)) { | |
$tag = strtolower($tag); | |
if (in_array($tag, $closing)) continue; // self closing tag | |
if ($close) $skip[] = $tag; | |
else { | |
if (end($skip) == $tag) array_pop($skip); | |
else $add[] = "</$tag>"; | |
} | |
} | |
return implode('', $add); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment