解析大括号内的文本,但不要停在内部右括号处?

发布于 2024-12-10 15:37:29 字数 562 浏览 1 评论 0原文

例如,

function hello(){
    echo 'hello';
    foreach (array(1,2,3) as $n)
    {
        echo $n;
    }
    echo 'bye-bye';
    echo 'bye-bye';
    echo 'bye-bye';
}
function hi(){}

我需要外大括号之间的所有内容,忽略任何内大括号,所以我的结果不会是这样的

{
    echo 'hello';
    foreach (array(1,2,3) as $n)
    {
        echo $n;
    }

或者

{
    echo 'hello';
    foreach (array(1,2,3) as $n)
    {
        echo $n;
    }
    echo 'bye-bye';
    echo 'bye-bye';
    echo 'bye-bye';
}
function hi(){}

exapmle

function hello(){
    echo 'hello';
    foreach (array(1,2,3) as $n)
    {
        echo $n;
    }
    echo 'bye-bye';
    echo 'bye-bye';
    echo 'bye-bye';
}
function hi(){}

I need everything that is between outer curly brackets, ignoring any inner curly brackets, so my result wont be like that

{
    echo 'hello';
    foreach (array(1,2,3) as $n)
    {
        echo $n;
    }

or

{
    echo 'hello';
    foreach (array(1,2,3) as $n)
    {
        echo $n;
    }
    echo 'bye-bye';
    echo 'bye-bye';
    echo 'bye-bye';
}
function hi(){}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陪我终i 2024-12-17 15:37:29

在一般情况下,这对于正则表达式是不可能实现的。您将需要使用专为该任务设计的解析器,或者编写您自己的解析器。

对于基本功能,您不需要太多:一次读取一个字符,记录在任何一点有多少个未闭合的大括号,并在该数字从 1 减少到 0 时考虑解析完成。

下一步是识别常见的字符串文字(单引号和双引号)并正确跳过这些字符串中的任何文字大括号,这足以让您完成 90% 的工作。

更新:这里是对类似问题的解答,其中还包括示例代码(尽管它是用 C# 而不是 PHP 编写的)。

In the general case this is not doable with regular expressions. You will need to use a parser designed for the task, or write one of your own.

For basic functionality you don't need much: read characters one at a time, keep a count of how many unclosed braces you have at any one point and consider parsing complete when this number decreases from 1 to 0.

The next step would be to recognize common string literals (single and double quoted) and correctly skip any literal braces in those strings, which would be enough to get you 90% of the way.

Update: here's an asnwer to a similar problem that also includes sample code (although it's in C# instead of PHP).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文