Regex pattern extract string between curly braces and exclude curly braces
$str='add[sometext]{begin{equation}label{eqn:3}
f_{1} =
begin{cases}}
beta_{1} + beta_{2}f_{2} & f_{2}leq gamma
beta_{1} + beta_{2}gamma + beta_{4}(f_{2}-gamma) & f_{2} >gamma
end{cases}sdsdssd,
end{equation}}
 it may have some extra code here with {}
 end{equation}}'
 I need to extract the string between add[sometext]{ and } (ietill add tag end curly braces)The string between add[sometext]{ and } may varies so I can't specify these string in regex pattern I should only consider starting and ending curly braces of add[sometext]  
Expected output:
begin{equation}label{eqn:3}
    f_{1} =
    begin{cases}
    beta_{1} + beta_{2}f_{2} & f_{2}leq gamma
    beta_{1} + beta_{2}gamma + beta_{4}(f_{2}-gamma) & f_{2} >gamma
    end{cases}sdsdssd,
    end{equation}
I tried:
 $str=preg_replace('/\adds*[s*w*]s*{(.*?)}/s,$1,$match) 
 I don't know how to get related curly braces (ie add tag start { till end } )  
这个怎么样:
$str='add[sometext]{begin{equation}label{eqn:3}
f_{1} =
begin{cases}
beta_{1} + beta_{2}f_{2} & f_{2}leq gamma
beta_{1} + beta_{2}gamma + beta_{4}(f_{2}-gamma) & f_{2} >gamma
end{cases}sdsdssd,
end{equation}}';
$str= preg_match('/\adds*[s*w*]s*{(.*?)}$/s',$str,$match);
var_dump($match[1]);
You can use a simple regex like this:
{([sS]*)}
Working demo

Match information
MATCH 1
1.  [21-226]    `begin{equation}label{eqn:3}
f_{1} =
begin{cases}}
beta_{1} + beta_{2}f_{2} & f_{2}leq gamma
beta_{1} + beta_{2}gamma + beta_{4}(f_{2}-gamma) & f_{2} >gamma
end{cases}sdsdssd,
end{equation}`
As you can see in the match information, the captured content is what you need.
The idea behind this regex is
{([sS]*)}
      ^--- Capture everything in a greedy way from the first `{` to the last `}`
 But also you can do the same thing if you use the s flag (single line):  
(?s){(.*)} --> using inline `s` flag
    {(.*)} --> using external `s` flag
For PHP code you can have:
$re = "@{(.*)}@s"; 
$str = "$str='add[sometext]{begin{equation}label{eqn:3}nf_{1} =nbegin{cases}}nbeta_{1} + beta_{2}f_{2} & f_{2}leq gammanbeta_{1} + beta_{2}gamma + beta_{4}(f_{2}-gamma) & f_{2} >gammanend{cases}sdsdssd,nend{equation}}'"; 
preg_match($re, $str, $matches);
Update:
You can use this regex for your updated comments in the question:
{([sS]*equation})}
Working demo
I have got a regex for my requirement.
 $str = preg_replace('/\adds*[.*]s*{(.*?)\end{(.[^s]*?)}}/s', "$1end{$2}", $str); 
Working demo
链接地址: http://www.djcxy.com/p/59512.html上一篇: 替换字符的首次和最后一次出现
