我想写一个正则表达式,
{protect}
{aa}
{/protect}
{aa}只替换未受{protect}保护的{aa}元素为abc 
可以实现吗?

解决方案 »

  1.   


    <?php
    $str='{protect}
    {aa}
    {/ptotect}
    {aa}';
    echo preg_replace("/(?<!{protect})\s*{aa}\s*(?!{\/protect})/",'111',$str);
    ?>
      

  2.   

    $str = <<<template
    {protect}
    {aa}
    {/protect}
    {aa} 
    template;
    $str = preg_replace("/\{protect\}(.*)\{\/protect\}/iseu",'str_replace("{aa}","abc","\\0")',$str);
    echo $str;
      

  3.   

    不知道是不是LZ的意思  $a = '{aa}{protect} 
    {aa} 
    {/protect} 
    {aa}{protect} 
    {aa} 
    {/protect} 
    {aa}';
       
       echo preg_replace('/({\/protect}[^\/{}]*|^[^\/{}]*){aa}([^\/{}]*{protect}|[^\/{}]*$)/is','${1}123$2',$a);
      

  4.   


    $str = <<<template
    {protect}
    {aa} {aa}
    {/protect}
    {aa} {aa}
    template;echo preg_replace("#(\{protect\}.*\{\/protect\}|\{aa\})#ise",'preg_replace("#^{aa}$#","abc","\\0")',$str);
      

  5.   

    有规律就可以吧
    <?php
    $str='
    {aa} 
    {protect} 
    {aa} 
    {/protect} 
    {aa} 
    ';
    $reg='/\{aa\}(?![^{]*\{\/protect\})/iU';
    $str = preg_replace($reg, 'abc', $str);
    echo $str;
    ?>