如何验证打开和关闭标签的数量? [英] how to validate the number of opened and closed tags?

查看:56
本文介绍了如何验证打开和关闭标签的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为每个"/< [a-z0-9] +>/i" 做一个preg_count,然后计算是否存在与闭合标签相同的数字,即:"/</[a-z0-9] +>/i"

I thought to do a preg_count for each "/<[a-z0-9]+>/i" and then count if exists the same number with the closed tags ie: "/</[a-z0-9]+>/i"

但是我不太确定.您将如何计算所有打开的标签并检查是否存在所有关闭的标签?

But I am not too sure. How would you count all opened tags and check if exists all closed tags?

Ps.我不需要检查属性和xml /> 单个结束标记.我只需要简单的简单html标签

Ps. i don't need to check for attribute and for xml /> single close tag. I just need a count on plain simple html tag

谢谢

推荐答案

我写了这个方便的函数.我认为如果我在一个preg_match_all中同时搜索打开/关闭的标签,可能会更快,但是因为这样更容易阅读:

I wrote this handy functions. I think it could be faster if I search both opened/closed tags within one preg_match_all but as this it's more readable:

<?php

//> Will count number of <[a-z]> tag and </[a-z]> tag (will also validate the order)
//> Note br should be in the form of <br /> for not causing problems
function validHTML($html,$checkOrder=true) {
    preg_match_all( '#<([a-z]+)>#i' , $html, $start, PREG_OFFSET_CAPTURE );
    preg_match_all( '#<\/([a-z]+)>#i' , $html, $end, PREG_OFFSET_CAPTURE );
    $start = $start[1];
    $end = $end[1];

    if (count($start) != count($end) )
        throw new Exception('Check numbers of tags');

    if ($checkOrder) { 
        $is = 0;
        foreach($end as $v){
            if ($v[0] != $start[$is][0] || $v[1] < $start[$is][1] )
                throw new Exception('End tag ['.$v[0].'] not opened');

            $is++;
        }
    }

    return true;
}

//> Usage::

try {
    validHTML('<p>hello</p><li></li></p><p>');

} catch (Exception $e) { 
    echo $e->getMessage();
}

请注意,如果您甚至需要捕捉带有数字的h1或任何其他标签,则需要在preg模式中添加0-9

Note if you need to catch even h1 or any other tag with numbers you need to add 0-9 within pattern of preg

这篇关于如何验证打开和关闭标签的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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