Recursively locate and close all open HTML tags automatically

.
This wonderful little PHP function searches through a string containing HTML elements, locates all the HTML tags, closes any that are open, and returns the string. We can’t take much credit for this given that we only modified what was originally done by another talented programmer (who we regrettably can’t credit due to a lack of details). However, it took us a little time to get something that worked just right.

This has been best deployed when using integrated text editors like Yahoo YUI 2: Rich Text Editor that typically leave tags open during user editing. We hope it will be just as useful for you as it has for the My PerPOS web architecture.

 PHP |  copy code |? 
  1. function closetags($html) {
  2. // Put all opened tags into an array
  3. preg_match_all('#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
  4. $openedtags = $result[1];   #put all closed tags into an array
  5. preg_match_all('#</([a-z]+)>#iU', $html, $result);
  6. $closedtags = $result[1];
  7. $len_opened = count($openedtags);
  8. # Check if all tags are closed
  9. if (count($closedtags) == $len_opened){
  10. return $html;
  11. }
  12. $openedtags = array_reverse($openedtags);
  13. # close tags
  14. for ($i=0; $i < $len_opened; $i++) {
  15. if (!in_array($openedtags[$i], $closedtags)){
  16. if($openedtags[$i]!='br'){
  17. // Ignores <br> tags to avoid unnessary spacing
  18. // at the end of the string
  19. $html .= '</'.$openedtags[$i].'>';
  20. }
  21. } else {
  22. unset($closedtags[array_search($openedtags[$i], $closedtags)]);
  23. }
  24. }
  25. return $html;
  26. }

Usage:

 PHP |  copy code |? 
  1. $withclosedtags = closetags("<your_string_with_html>");

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>