如何检查每个 HTML 标签是否已关闭? [英] How can i check if every HTML tag is closed?

查看:40
本文介绍了如何检查每个 HTML 标签是否已关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题:

用户可以添加 HTML 描述,它将显示在他的个人资料中;当我显示用户列表时,我也希望显示此描述.
因为它可能太长,我将把它限制在一个固定的长度,但这样做我可能会破坏 HTML 语法而留下一些标签.

user can add an HTML description and it will be shown on his profile; when i show the user list, i'd wish to show this description, too.
since it could be too long, i'm going to cap it to a fixed lenght, but doing this i could break the HTML syntax leaving some tags open.

我如何检查一切是否正常,并在需要时关闭任何打开的标签?

how can i check if everthing is ok and, if needed, close any open tag?

推荐答案

@tampe125 这不是我的代码,但它看起来有效.

@tampe125 This isn't my code, but it looks like it works.

  <?php  /** * close all open xhtml tags at the end of the string

 * * @param string $html

 * @return string

 * @author Milian <mail@mili.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;}  ?>

这篇关于如何检查每个 HTML 标签是否已关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆