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:
"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 . 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).
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);
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. Again, this can be done with string operations itself, using substr
and strrpos
.
I think you can use the split Function.E then you can use the Replace .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.