如何跳过特定行preg_replace - PHP

时间:2014-03-05 12:59:57

标签: php regex

我创建了一个从字符串中删除多余空格的小函数

/* remove white space */
function wspace($string){

    $string = preg_replace( '/\s+/', ' ', $string);
    return $string;
}

它运作得很好,但我遇到的问题是: 如果我在js字符串上使用此函数,那么就会有像

这样的提交行
// will brake js output, 

示例

      $js_string .="
        window.addEvent('load', function(){
            new Drop({
                container:'container',
                offset: ".$offset.", // top menu offset
                width:200
            });
        });
      ";

echo wspace( $js_string );

这将输出

window.addEvent('load', function(){ new Drop({ container:'container',offset: ".$offset.", // top menu offset width:200 }); });";

//

之后评论所有内容

我如何使用/*或任何不会弄乱其余代码的内容来跳过或替换这些行?

我知道用//评论/*替换*/是应该做的,但我正在对我广泛使用的旧脚本进行更新,我不知道是否用户有//或/ *评论*/。因此,为了不破坏别人的代码,我需要确定在发布之前。

我想做点什么

if($string contains // ) skip to next line 

或您认为可以使此功能更安全的任何内容。

感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用此模式:

$pattern = <<<'EOD'
~
# this first part skips content between quotes
(["']) (?>[^'"\\]+|\\.|(?!\1)["'])* \1 (*SKIP)(*FAIL)
|
# this part matches comments and capture the content in group 2
//(\N*)
|
# this part matches whitespace characters
\s+
~xs
EOD;

然后将其与preg_replace_callback()

一起使用
$result = preg_replace_callback($pattern, function ($m) {
     return ($m[2]) ? '/* ' . trim($m[2]) . ' */' : ' ';
}, $data);

print_r($result);

答案 1 :(得分:1)

你可以试试这个。 preg_replace可以将数组作为模式并替换。

function wspace($string){
    $string = preg_replace( array('/[^:]\/\/.*$/m','/\/\*.*\*\//U', '/\s+/'), array('','',' '), $string);
    return $string;
}

编辑:

如果您还想从脚本中删除/ * ... * /注释,可以使用此

function wspace($string){
    echo $string;
    $string = preg_replace( array('/[^:]\/\/.*$/m','/\/\*.*\*\//U', '/\s+/'), array('','',' '), $string);
    return $string;
}

注意:我没有在真正的javascript函数上测试过这些 编辑:使其://url...安全。