使用preg_replace实时添加行

时间:2014-03-20 10:46:50

标签: php string function preg-replace eof

我想知道是否可以在preg_replace中获取正则表达式匹配并实时操作它(哇...在相同的preg_replace命令中)...

这不是正确的语法,只是为了得到这个想法......

    $test = <<<EOF

    <!--

    THIS IS COMMENT #1

    -->

    <!--

    THIS IS COMMENT #2

    -->
    EOF;

    $test = preg_replace('#<--(.|\s)*?-->#', 'Additional line to the html comment without delete the real comment' . '#<--(.|\s)*?-->#' .'<BR/>' , $test);

    //iow... how can I replace this '#<--(.|\s)*?-->#'
//to this : 'Additional line to the html comment without delete the real comment' . '#<--(.|\s)*?-->#' .'<BR/>'

    echo $test;

    /*
    I expect to get this :

    <!--
    Additional line to the html comment without delete the real comment
    THIS IS COMMENT #1

    -->

    <!--
    Additional line to the html comment without delete the real comment
    THIS IS COMMENT #2

    -->
    */

有什么想法吗? :/

2 个答案:

答案 0 :(得分:0)

怎么样:

$test = preg_replace('#(<--)(.+?)(-->)#', '$1Additional line to the html comment without delete the real comment$2$3' , $test);

答案 1 :(得分:0)

如果您的评论在开头时总是有两个换行符,那么快速使用正则表达式:

$trans = array("<!--\n\n" => "<!--\n$newline",
               "<!--\r\n\r\n" => "<!--\r\n$newline");

$str = strtr($str, $trans);