doulu8446 2016-07-14 16:37
浏览 8
已采纳

解析和验证自定义的方法

I my application I have custom tags that contains other tags. Example:

I have a tag named {BIG} that can contain text and subtags like {BIG2} text {/BIG2}

A {BIG2} parent can be only an {BIG} tag a {BIG3} parent should be a {BIG3}.

I hope it makes sense.

My current approach is to iterate the whole text and check for the { character and make sense if its the opening or closing tag.

for ( $i = 0; $i < strlen( $this->input ); $i++ ) {
            $char = $this->input[$i];

            if ($char == '{') {
                if ($this->input[$i + 1] == '/') {
                    // close tag
                    echo 'close tag on pos: ' . ($i + 1);
                } else {
                    // open tag
                }
            }
        }

My problem is this approach seems very fragile and laborious and I was wondering if I am on correct curse?

I don't the solution because I am doing this as an exercise. I just want to know that this is the correct approach to solve the problem.

  • 写回答

1条回答 默认 最新

  • dongxi1320 2016-07-14 17:09
    关注

    If you're doing if as an exercise it maybe an opportunity to figure out how to create a state machine out of this. The way it works is that you create a matrix, on one side of it are "states" and on another "events", the intersection of the matrix can either be a function to perform or (if you only need to validate) the next state.

    The events here could be your characters: '{', '}', '/', and 'anything else'. The states are a bit more complicated NOTAG, TAGSTARTED, INTAG, TAGCLOSING, etc.

    Depending upon your goal it maybe easier to make a non-deterministic state machine; then you would add a stack, where you can store the tags you're already in, and that stack can be operated by the functions. For example, when you enter into {BIG}, you put that on the stack, then when a new tag is read you can check the top of the stack, and if everything is ok add the new tag on the top of it; when you close tags you can pop the tags from the said stack (potentially checking that the closing tag matches the opened one).


    I hope that this will help a little; it's difficult to answer such an open-ended question.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 优质github账号直接兑换rmb,感兴趣伙伴可以私信
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)