正则表达式删除Javascript String Continuation

时间:2015-04-18 12:34:21

标签: regex

我有一些没有在Google Closure中编译的javascript,因为它中有字符串延续。我试图用正则表达式删除斜线和新行字符,但我无法在谈话标记之间找到它。

以下是javascript的示例:

var test = '<div class="pp_pic_holder"> \
<div class="ppt">&nbsp;</div> \
</div>';

这就是我到目前为止所做的:

preg_replace("/\\r?\n|\r/", "", $input_lines);

1 个答案:

答案 0 :(得分:0)

为了能够在javascript源代码中找到字符串,您还必须能够找到注释。注释可能包含引号,字符串可能包含斜杠。

整个过程最简单,只需两次更换:

preg_replace_callback(
    '#//[^\\r\\n]*|/\\*.*?\\*/|("(?:\\\\.|[^\\\\"])*"|\'(?:\\\\.|[^\\\\\'])*\')#s',
    function ($matches) {
        $str = $matches[1];

        // Return comments unmodified
        if (empty($str)) return $matches[0];

        // Remove line-continuations from strings:
        return preg_replace('#\\\\(?:\\r\\n?|\\n)#', '', $str);
    },
    $jscode);

演示:http://ideone.com/qcm8sB