正则表达式替换php中开始和结束标记之外的所有内容

时间:2014-02-16 15:09:14

标签: php regex preg-replace

我已经为字符串

定义了我的开始和结束标记
!R= //Start Tag of R
=R! //End Tag of R

!G= //Start Tag of G
=G! //End Tag of G

我想替换这两个标签之外的所有内容(字符串)。假设我的字符串就像

<div>
   I am going to be replaced
   !R= Hello World =R!
   I am being replaced
   !G= I will be safe =G!
   I have replaced
</div>

我不需要任何缩进只是替换了我定义的标签之外的所有内容。输出可以是这样的

@<div>
   I am going to be replaced@
   !R= Hello World =R!
   @I am being replaced@
   !G= I will be safe =G!
   @I have replaced
</div>@

目前我正在使用像

这样的jugars
$str  = '!N-'.$str.'-N!';
$str = str_replace(array('!R-', '-R!'), array('-N!!R-', '-R!!N-'), $str);   
$str = preg_replace_callback("~!N-(.+?)-N!~s", function($matches) 
{
    return str_replace('!N-'.$matches[1].'-N!', "@a" . $matches[1] . "@a", $matches[0]);
}, $str);

$str = str_replace(array('!N-','-N!'), '', $str);   

这很有用,但是单个字符串需要0.12秒:(

2 个答案:

答案 0 :(得分:3)

好像我用first regex过度复杂化了。只需使用这个:

(.+?)            # Match anything one or more times ungreedy (group 1)
(?:              # Non-capturing group
   (             # Group 2, here we add our exceptions
      !R=.*?=R!
      |
      !G=.*?=G!
   )             # End group 2
   |             # Or
   $             # End of line
)                # End of non-capturing group

不要忘记使用这些修饰符

  • x:用于格式化和评论。
  • s:将新行与.(点)匹配。

替换为@$1@$2

在PHP中它看起来像:

$input = '<div>
   I am going to be replaced
   !R= Hello World =R!
   I am being replaced
   !G= I will be safe =G!
   I have replaced
</div>';

$regex = '~
(.+?)            # Match anything one or more times ungreedy (group 1)
(?:              # Non-capturing group
   (             # Group 2, here we add our exceptions
      !R=.*?=R!
      |
      !G=.*?=G!
   )             # End group 2
   |             # Or
   $             # End of line
)                # End of non-capturing group
~xs';
$output = preg_replace($regex, '@$1@$2', $input);

echo $output;

你答应我学习正则表达式。我期待着它 <子> MWA 公顷公顷 公顷 公顷 功能

够笑了,这是 online demo

答案 1 :(得分:0)

我能用一个稍微简单的正则表达式来做到这一点:

$str = '
<div>
   I am going to be replaced
   !R= Hello World =R!
   I am being replaced
   !G= I will be safe =G!
   I have replaced
</div>
';

$regex = '/(\s*!(.+)=[^=]*=\2!\s*)/';

$result = '@' . preg_replace($regex, '@\1@', trim($str)) . '@';
$result = str_replace('@@', '', $result);
echo $result;