MW

Tag tags

Recent Posts

Close HTML Tags (June 16, 2007)

If you cut a html-formatted string at some random position (e.g. with my truncate() function) you might mess up the html. To circumvent that, this function will close all open tags at the end of the string:

The original function was written by connum at DONOTSPAMME dot googlemail dot com

    /**
     * close all open xhtml tags at the end of the string
     *
     * @param string $html
     * @return string
     * @author Milian Wolff <mail@milianw.de>
     */
    function closetags($html) {
      #put all opened tags into an array
      preg_match_all('#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
      $openedtags = $result[1];
     
      #put all closed tags into an array
      preg_match_all('#</([a-z]+)>#iU', $html, $result);
      $closedtags = $result[1];
      $len_opened = count($openedtags);
      # all tags are closed
      if (count($closedtags) == $len_opened) {
        return $html;
      }
      $openedtags = array_reverse($openedtags);
      # close tags
      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;
    }

continue reading...