Skip to content

Instantly share code, notes, and snippets.

@JayWood
Created July 18, 2014 20:17
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save JayWood/348752b568ecd63ae5ce to your computer and use it in GitHub Desktop.
Save JayWood/348752b568ecd63ae5ce to your computer and use it in GitHub Desktop.
Close ALL open HTML tags in PHP string
<?php
function closetags($html) {
preg_match_all('#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
$openedtags = $result[1];
preg_match_all('#</([a-z]+)>#iU', $html, $result);
$closedtags = $result[1];
$len_opened = count($openedtags);
if (count($closedtags) == $len_opened) {
return $html;
}
$openedtags = array_reverse($openedtags);
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;
}
@Lovely-Fellow
Copy link

Lovely-Fellow commented Sep 1, 2023

@JayWood Code is great! But it's not closing h tags such as h1, h2, h3, h4, h5 and h6.
Here are updated code.

function closetags($html) {
    preg_match_all('#<([a-zA-Z0-9]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
    $openedtags = $result[1];
    preg_match_all('#</([a-zA-Z0-9]+)>#iU', $html, $result);

    $closedtags = $result[1];
    $len_opened = count($openedtags);

    if (count($closedtags) == $len_opened) {
        return $html;
    }
    $openedtags = array_reverse($openedtags);
    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;
}

@wpexplorer
Copy link

Great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment