Find coresponding open/close brackets

余生长醉 提交于 2019-12-25 01:59:40

问题


A follow up on a previous question: PHP how to best edit an RTF File

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.

Thanks jason


回答1:


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);

Output:

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


来源:https://stackoverflow.com/questions/22224587/find-coresponding-open-close-brackets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!