Replacing tags in braces, even nested tags, with regex

前端 未结 3 1128
感情败类
感情败类 2021-01-26 08:36

Example

preg_replace(\'/\\{[a-zA-Z.,\\(\\)0-9]+\\}/\', \'Replaced\', \'Lorem ipsum dolor sit {tag1({tag2()})}, consectetur adipiscing elit.\');
         


        
相关标签:
3条回答
  • 2021-01-26 09:11

    You might want to use T-Regx:

    <?php
    $subject = 'Lorem ipsum dolor sit {tag1({tag2()})}, consectetur adipiscing elit.';
    
    pattern('\{[a-zA-Z.,()0-9]+\}')->replace($subject)->first()->with('Replaced');
    
    0 讨论(0)
  • 2021-01-26 09:22

    You need to add curly braces to your character set. Here's the pattern I used:

    /\{[a-zA-Z.,\(\)\{\}0-9]+\}/
    

    And here was the result:

    "Lorem ipsum dolor sit Replaced, consectetur adipiscing elit."
    
    0 讨论(0)
  • 2021-01-26 09:29

    Once you start talking about matching nested patterns (eg: matching the inner bracketed group in something like (foo (bar) fu)), then regex is the wrong tool. Regular Expressions are stateless, which, in this case, means that they can't count how many brackets are open.

    If you are looking to do something like that, you might need to look into a parser

    0 讨论(0)
提交回复
热议问题