Search code examples
phppreg-match

preg_match - console.log removing


This is the scenario:

  1. JS file is loaded into string using file_get_contents
  2. I want to remove all debugging info from it
  3. For the purpose of finding out whats happening in PHP code I am using preg_match

I'm using this expression:

(\/\/)?(\s*?)console\.(log|debug|info|log|warn|error|assert|dir|dirxml|trace|group|groupEnd|time|timeEnd|profile|profileEnd|count)\((.*?[^}(])\);?$

On regex101 and phpliveregex websites it matches:

//console.log(abc)
//   console.log(abc)
// console.log(abc);
// console.log('abc');
console.log(abc);
console.log('abc' + some_function());
etc...

But when I put it in PHP code like this:

preg_match('/(\/\/)?(\s*?)console\.(log|debug|info|log|warn|error|assert|dir|dirxml|trace|group|groupEnd|time|timeEnd|profile|profileEnd|count)\((.*?[^}(])\);?$/', $js_code, $matches);
if (!empty($matches[0])) print_r($matches[0]);

I dont get any matches. Too tired to notice what am I missing. Probably something staring at me with its big eyes. :) Any help would be appreciated.


Solution

  • After some further investigation I improved my regex pattern to match every combination.

    @Jan

    Your answer pushed me in the right direction.

    ((\/\/)?(\s*?)console\.(log|debug|info|log|warn|error|assert|dir|dirxml|trace|group|groupEnd|time|timeEnd|profile|profileEnd|count)(\s*?)\((.*[^}(])(\){1,});?)