找到对应的开/关括号 [英] Find coresponding open/close brackets

查看:53
本文介绍了找到对应的开/关括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对上一个问题的跟进:PHP 如何最好地编辑一个 RTF 文件

我相信我有解决方案,但需要更多帮助.我发现如果我在模板构建器中使用合并字段,我的 php 代码可以找到/替换这种模式中的字段:{\field}" 但是,问题是我需要找到整个字符串,删除所有 RTF 标签,并比较留下的文本.不过,第一步是找到完整的标记.这就是我被困的地方.我需要能够找到整个字符串长度,从打开的{"到关闭的}",中间可能还有其他的{}"集.例如:

I believe I have a solution, but need some more help. I found that if I use merge fields in my template builder, my php code could find/replace fields that are in this pattern: "{\field}" The problem is, though, that I would need to find the whole string, remove all RTF tags, and compare the text left behind. The first step, though, is to find the full markup. And this is where I am stuck. I would need to be able to find the entire string length, from open "{" to close "}", with possible other sets of "{}" in between. For example:

{\field{\*\fldinst {\rtlch\fcs1 \af31507 \ltrch\fcs0 \insrsid11370280  MERGEFIELD details_awardee_name }}{\fldrslt {\rtlch\fcs1 \af31507 \ltrch\fcs0 
\lang1024\langfe1024\noproof\insrsid11370280 \'abdetails_awardee_name\'bb}}}

如您所见,此示例具有多个嵌入式标记集.此字符串也将位于更多标记的页面内.有谁知道获得整个字符串长度的方法?这可以用正则表达式完成吗?完成此操作后,我可以继续剥离所有标签并进行比较.

As you can see, this example has multiple embedded markup sets. This string would also be within pages of more markup. Does anyone know a way to get the entire string length? Can this be done with Regex? Once I get this accomplished, I can move on to stripping all tags and comparing.

谢谢杰森

推荐答案

您可以使用 递归模式 可用于选项 PCRE_EXTENDED (x).举个例子:

You can use a recursive pattern available with the option PCRE_EXTENDED (x). Here comes an example:

$str = 'test { enclosed { sub   }} end';
$p = '~\{ ( (?>[^{}]+) | (?R) )* \}~x';

preg_match_all($p, $str, $m);
var_dump($m);

输出:

array(2) {
  [0] =>
  array(1) {
    [0] =>
    string(21) "{ enclosed { sub   }}"
  }
  [1] =>
  array(1) {
    [0] =>
    string(9) "{ sub   }"
  }
}

这篇关于找到对应的开/关括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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