解析大括号内的文本,但不要停在内部右括号处?
例如,
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在一般情况下,这对于正则表达式是不可能实现的。您将需要使用专为该任务设计的解析器,或者编写您自己的解析器。
对于基本功能,您不需要太多:一次读取一个字符,记录在任何一点有多少个未闭合的大括号,并在该数字从 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).