2010-08-11 75 views
0

我想用preg_replace替换“* @license until */”与“testing”。
我该怎么做?
我的文字是下面的一个:preg_replace特定模式

/* 
* @copyright 
* @license 
* 
*/ 

我希望大家有正确地理解我的问题。

回答

0

好吧,这不是太难。所有你需要做的就是使用s修饰符(PCRE_DOT_ALL,这使得.在正则表达式匹配新行):

$regex = '#\\*\\s*@license.*?\\*/'#s'; 
$string = preg_replace($regex, '*/', $string); 

这应该为你工作(注意,未经测试)...

2

这里是你想要做什么(在多行模式下运行)一个正则表达式

 
^\s*\*\s*@license(?:(?!\s*\*/)[\s\S])+ 

它被删除线的部分相匹配:

 
/* 
* @copyright 

            
 
  
             * @license 
*
            
  
*/ 

说明:

 
^    ~ start-of-string 
\s*   ~ any number of white space 
\*    ~ a literal star 
\s*   ~ any number of white space 
@license  ~ the string "@license" 
(?:   ~ non-capturing group 
    (?!   ~ negative look ahead (a position not followed by...): 
    \s*  ~  any number of white space 
    \*   ~  a literal star 
    /  ~  a slash 
)   ~ end lookahead (this makes it stop before the end-of-comment) 
    [\s\S]  ~ match any single character 
)+    ~ end group, repeat as often as possible 

注意,正则表达式还必须根据PHP字符串规则根据preg_replace()规则进行转义。

编辑:如果你喜欢它 - 使绝对确保,真的有结束注释的标记以下匹配的文本,正则表达式可以展开如下:

 
^\s*\*\s*@license(?:(?!\s*\*/)[\s\S])+(?=\s*\*/) 
             ↑   positve look ahead for 
             +-----------an end-of-comment marker 
+0

非常有帮助方法来解释正则表达式的语法,thx – 2013-01-23 10:37:09