dtfbj24048 2016-06-29 15:35
浏览 37
已采纳

如何在括号之间获取所有内容,但只包括那些未包含在括号中的内容

By now i'm using regex: '/{(.*?)}/' to get everything inside curly barackets in strings like: 'abc {get me} def {and get me}' which works fine.

Now i'm looking for a way to exclude brackets, which are surrounded by brackets themselves. The string should be self-explanatory: 'abc {get me {!but not me!}} def {and get {!but not me again!} me} ghi'.

The following code should illustrate my needs...

<?php
$regex  = '/{(.*?)}/';
$string = 'abc {get me {!but not me!}} def {and get {!but not me again!} me} ghi';
preg_match_all( $regex, $string, $matches );
print_r( $matches[1] );
?>

prints:

Array
(
    [0] => get me {!but not me!
    [1] => and get {!but not me again!
)

but should be:

Array
(
    [0] => get me {!but not me!}
    [1] => and get {!but not me again!} me
)

Until now i was not able to find a solution via Google and looking forward to get one at SO.

regards

EDIT: Actually a very similar question was asked and answered on SO. But if you are not familiar with regex it's really hard to change from wrapper (...) to {...}. So you can not simply take the one pattern given by the answer (see link above) and search-replace all '(' & ')' with '{' & '}'. You really have to understand what's going on there.

But if you understand this pattern enough to customize it you probably would be able to write it on your own...

  • 写回答

2条回答 默认 最新

  • douxiangshi6568 2016-06-29 16:00
    关注

    You need a recursive regex with a capturing group that would capture the contents inside the curly braces:

    {((?:[^{}]++|(?R))*)}
    

    Explanation:

    • { - a literal { (in PHP PCRE, you do not need to escape this character)
    • ( - Start of the capturing group 1
      • (?:[^{}]++|(?R))* - zero or more sequences (see (?:...)*) of 1+ characters other than { and } (see [^{}]++) or the whole pattern ((?R) is a placeholder for the whole pattern, like (?0) subroutine call)
    • ) - end of Group 1
    • } - closing literal }

    See the regex demo and the PHP demo:

    $re = '~{((?:[^{}]++|(?R))*)}~'; 
    $str = "abc {get me {!but not me!}} def {and get {!but not me again!} me} ghi"; 
    preg_match_all($re, $str, $matches);
    print_r($matches[1]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度