简体   繁体   English

使用正则表达式从字符串返回第一个外部结果

[英]Return first outer result from a string, using regular expressions

I have the following string: 我有以下字符串:

"{My {formatted {hi|hello}|formate{hi|hello} }  {option 1|option 2|option 3}}";

I want find the result in-between the "{" and "}" brackets. 我想在“ {”和“}”括号之间找到结果。

Also result should be from the outer layer, not {hi|hello} but: 结果也应该来自外层,而不是{hi|hello}而是:

"My {formatted {hi|hello}|formate{hi|hello} }  {option 1|option 2|option 3}"

You can extract the most outer content from an indeterminate level number of nested brackets with this pattern: 您可以使用这种模式从不确定数量的嵌套括号中提取最外部的内容:

$pattern = '~{((?>[^{}]++|(?R))+)}~';

where (?R) means repeat the whole pattern . 其中(?R)表示重复整个模式 It is a recursive approach. 这是一种递归方法。
If you need the same to use as subpattern in a larger expression, you must use: 如果需要在较大的表达式中将其用作子模式,则必须使用:
({((?>[^{}]++|(?-2))+)}) since the (?-2) is a relative reference to the second capturing group on the left (the first here). ({((?>[^{}]++|(?-2))+)})因为(?-2)是相对于左侧第二个捕获组(此处是第一个捕获组(?-2)的相对引用。

Pattern details: 图案细节:

 (             # first capturing group
   {           # literal {
   (           # second capturing group (what you are looking for)
     (?>       # atomic group
       [^{}]++ # all characters except { and }, one or more time
      |        # OR
       (?-2)   # repeat the first capturing group (second on the left)
     )+        # close the atomic group, repeated 1 or more time
   )           # close the second capturing group
   }           # literal }
 )             # close the first capturing group

/^{(.*)}$/ would remove the first and last { and } /^{(.*)}$/将删除第一个和最后一个{}

used via $var = preg_replace('/^{(.*)}$/', '$1', $your_text); 通过$var = preg_replace('/^{(.*)}$/', '$1', $your_text);

That particularly can be made with basic string operations too, you could advance that regex to /^[^{]*{(.*)}[^{]*$/ which would let you put chars in front of the desired string and after it. 特别是也可以通过基本的字符串操作来实现,您可以将该正则表达式提升为/^[^{]*{(.*)}[^{]*$/ ,这可以让您将chars放在所需的字符串前面,然后之后。 Again, this can be done with string operations itself, using substr and strrpos . 同样,这可以通过使用substrstrrpos进行字符串操作本身来完成。

I think you can use the split Function.E then you can use the Replace . 我认为您可以使用split Function.E然后可以使用Replace

http://php.net/manual/pt_BR/function.split.php http://php.net/manual/pt_BR/function.split.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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