Posted By

wellynz on 09/08/10


Tagged


Versions (?)

Close tags


 / Published in: PHP
 

Closes opened HTML tags.

  1. function closetags($html) {
  2. preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
  3. $openedtags = $result[1];
  4. preg_match_all('#</([a-z]+)>#iU', $html, $result);
  5. $closedtags = $result[1];
  6. $len_opened = count($openedtags);
  7. if (count($closedtags) == $len_opened) {
  8. return $html;
  9. }
  10. $openedtags = array_reverse($openedtags);
  11. for ($i=0; $i < $len_opened; $i++) {
  12. if (!in_array($openedtags[$i], $closedtags)) {
  13. $html .= '</'.$openedtags[$i].'>';
  14. } else {
  15. unset($closedtags[array_search($openedtags[$i], $closedtags)]);
  16. }
  17. }
  18. return $html;
  19. }

Report this snippet  

You need to login to post a comment.