简体   繁体   中英

PHP preg_match_all: brackets tags inside brackets tags

I have my custom tags, for ex.

{{tag-name}}
<table>
  <tr>
    {{loop}}<td>text</td> ... {{/loop}}
  </tr>
</table>
{{/tag-name}}

I want to extract HTML code inside bracket tags.

I use this pattern in preg_match_all:

/{\{.*?\}\}((?:(?!\{\{/(.*?)\}\}).)*)\{\{\/.*?\}\}/s

but it doesn't work. How can I fix this?

If the {{tag-name}} is not arbitrary nested, this regex should do it:

$pattern = '~{{([^}]+)}}(.*?){{/\1}}~s';

See on regex101.com

Captures the tag-name in first parenthesised group {{([^}]+)}} and matches the end {{/\\1}}

Captured matches of 2nd parenthesised group (.*?) will be in $out[2]

Using s (PCRE_DOTALL) modifier and *? lazy quantifier .


Use with preg_match or preg_match_all if desired, eg

if(preg_match_all($pattern, $input, $out)) {
   var_dump($out);
}

See eval.in for an example .

get your father's tags with preg_match_all and "/\\{\\{.[^\\}]+\\}\\}(.+)\\{\\{\\/.+\\}\\}/s" regex; the problem is your tag inside another tag.

Look DomDocument at http://php.net/manual/en/class.domdocument.php is to easy to load your document, get tags inside document, and tags content, with a simple method call...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM