我有以下字符串:返回第一外結果從一個字符串,使用正則表達式
"{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}"
我有以下字符串:返回第一外結果從一個字符串,使用正則表達式
"{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}"
/^{(.*)}$/
將消除經由$var = preg_replace('/^{(.*)}$/', '$1', $your_text);
即尤其可以由使用的第一和最後一個{
和}
通過基本的字符串操作,您可以將該正則表達式提前到/^[^{]*{(.*)}[^{]*$/
,這會讓您將字符放在所需的字符串前面之後。再次,這可以使用字符串操作本身完成,使用substr
和strrpos
。
我認爲你可以使用分割 Function.E然後你可以使用替換。
可以提取與該圖案嵌套括號的不確定電平數目的最外面的內容:
$pattern = '~{((?>[^{}]++|(?R))+)}~';
其中(?R)
裝置重複整個圖案。這是一種遞歸方法。
如果您需要使用與較大表達式中相同的子模式,則必須使用:({((?>[^{}]++|(?-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
+1用於建議使用子模式。 – anubhava
請添加一些例子 –
所以你要刪除的外'{}'?爲什麼不呢:'$ str = substr($ str,1,-1);'? –
只需剝離牙套;沒有? – mshsayem