Code to close any HTML tags that are not-closed in a string


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function closetags ( $html )
  2. {
  3. $html = strrpos ( $html, "<" ) > strrpos ( $html, ">" ) ? rtrim ( substr ( $html, 0, strrpos ( $html, "<" ) ) ) : rtrim ( $html );
  4.  
  5. #put all opened tags into an array
  6. preg_match_all ( "#<([a-z]+)( .*)?(?!/)>#iU", $html, $result );
  7. $openedtags = $result[1];
  8.  
  9. #put all closed tags into an array
  10. preg_match_all ( "#</([a-z]+)>#iU", $html, $result );
  11. $closedtags = $result[1];
  12. $len_opened = count ( $openedtags );
  13. # all tags are closed
  14. if( count ( $closedtags ) == $len_opened )
  15. {
  16. return $html;
  17. }
  18. $openedtags = array_reverse ( $openedtags );
  19. # close tags
  20. for( $i = 0; $i < $len_opened; $i++ )
  21. {
  22. if ( !in_array ( $openedtags[$i], $closedtags ) )
  23. {
  24. $html .= "</" . $openedtags[$i] . ">";
  25. }
  26. else
  27. {
  28. unset ( $closedtags[array_search ( $openedtags[$i], $closedtags)] );
  29. }
  30. }
  31. return $html;
  32. }
  33.  
  34. $snippet = "<div>This is some interesting <strong><em>content!";
  35.  
  36. $x = closetags ( $snippet );
  37.  
  38. print htmlspecialchars ( $x );

URL: http://snipplr.com/view/3618/close-tags-in-a-htmlsnippet/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.