PHP regexp - 检测未闭合的括号 [英] PHP regexp - Detect unclosed brackets

查看:25
本文介绍了PHP regexp - 检测未闭合的括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检测一个字符串是否包含任何未闭合的尖括号.

我试图通过比较左右括号的数量来避免正则表达式:

if (substr_count($string, '<') !== substr_count($string, '>')){//文本包含未闭合的尖括号}

但是这种方法不会检测到这样的错误:

这是>b<BOLD>/b<单词

解决方案

对于这样的任务,我不建议使用正则表达式.
快速编写了一个简单的函数来检查字符串中是否有正确书写的括号:

/*** @param $str 输入字符串* @returns boolean 如果所有括号都正确打开和关闭,则为 true,否则为 false*/函数 checkBraces($str){$strlen = strlen($str);//缓存字符串长度以提高性能$openbraces = 0;for ($i = 0; $i < $strlen; $i++){$c = $str[$i];if ($c == '<')//计数左括号$openbraces++;if ($c == '>')//计数右括号$openbraces--;if ($openbraces < 0)//检查未打开的右括号返回假;}返回 $openbraces == 0;//检查未闭合的开括号}

使用此代码作为基础,实施检查以验证左括号和右括号的标签名称是否也匹配应该不会太难 - 但我会留给你:-)

I need to detect if a string contains any unclosed angle brackets.

I tried to avoid regular expression by comparison number of left and right brackets:

if (substr_count($string, '<') !== substr_count($string, '>'))
{
    // Text contains unclosed angle brackets           
}

But this method will not detect mistake like this:

This is >b<BOLD>/b< word

解决方案

I would not recommend using regular expressions for a task like this.
A simple function to check a string for properly written brackets is quickly written:

/**
* @param $str input string
* @returns boolean true if all brackets are properly opened and closed, false otherwise
*/
function checkBraces($str)
{
    $strlen = strlen($str); // cache string length for performance
    $openbraces = 0;

    for ($i = 0; $i < $strlen; $i++)
    {
        $c = $str[$i];
        if ($c == '<') // count opening bracket
            $openbraces++;
        if ($c == '>') // count closing bracket
            $openbraces--;

        if ($openbraces < 0) // check for unopened closing brackets
            return false;
    }

    return $openbraces == 0; // check for unclosed open brackets
}

Using this code as a basis, it shouldn't be too hard to implement a check to verify whether or not the tag name of opening and closing brackets also matches - but I'll leave that to you :-)

这篇关于PHP regexp - 检测未闭合的括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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