![](/img/trans.png)
[英]PHP regular expressions to extract a nested expression first then the outer expression
[英]Return first outer result from a string, using regular expressions
我有以下字符串:
"{My {formatted {hi|hello}|formate{hi|hello} } {option 1|option 2|option 3}}";
我想在“ {”和“}”括號之間找到結果。
結果也應該來自外層,而不是{hi|hello}
而是:
"My {formatted {hi|hello}|formate{hi|hello} } {option 1|option 2|option 3}"
您可以使用這種模式從不確定數量的嵌套括號中提取最外部的內容:
$pattern = '~{((?>[^{}]++|(?R))+)}~';
. 其中(?R)
表示 。 這是一種遞歸方法。
如果需要在較大的表達式中將其用作子模式,則必須使用:
({((?>[^{}]++|(?-2))+)})
因為(?-2)
是相對於左側第二個捕獲組(此處是第一個捕獲組(?-2)
的相對引用。
圖案細節:
( # 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
/^{(.*)}$/
將刪除第一個和最后一個{
和}
通過$var = preg_replace('/^{(.*)}$/', '$1', $your_text);
特別是也可以通過基本的字符串操作來實現,您可以將該正則表達式提升為/^[^{]*{(.*)}[^{]*$/
,這可以讓您將chars放在所需的字符串前面,然后之后。 同樣,這可以通過使用substr
和strrpos
進行字符串操作本身來完成。
我認為您可以使用split Function.E然后可以使用Replace 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.