【问题标题】:How can i check if every HTML tag is closed?如何检查每个 HTML 标签是否已关闭?
【发布时间】:2011-11-24 14:57:31
【问题描述】:

我有这个问题:

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

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

【问题讨论】:

    标签: php validation xhtml


    【解决方案1】:

    @tampe125 这不是我的代码,但看起来可以。

      <?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;}  ?>
    

    【讨论】:

    • 不客气,它似乎会起作用,虽然我还没有尝试过。我从kirupa.com/forum/showthread.php?343478-Close-all-open-HTML-tags得到了答案
    • 正则表达式永远不是匹配 HTML 的正确解决方案。 Tidy 可能更适合你。
    • @kevinji 我现在知道它很久了,但你是什么意思正则表达式永远不是正确的解决方案?使用库而不是普通 php 是 2011 年的事情吗?
    【解决方案2】:

    这是一个简单的 javascript 验证器,可以进行基本的标签检查。 XML validator

    唯一的问题是它会在第一个错误处停止,因此您需要一次解决一个问题。

    【讨论】:

      猜你喜欢
      • 2012-01-15
      • 2012-01-29
      • 1970-01-01
      • 2010-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      相关资源
      最近更新 更多