0

I need to identify the start and end of function definitions (blocks) in Javascript source code, using PHP. I don't need to parse the code, just literally know where the beginning and end of the Javascript code is if I've read it into a PHP string (using file_get_contents() for example, or some other way).

I need to only identify functions defined at the highest level within the global scope of the Javascript code, and also functions defined at that level for JQuery event callbacks, but I need to ignore more embedded functions in the code.

So, e.g.

function my_JS_func()
{
// some code
}

and

$('#button').onclick(click(function(e){
// some code
});

but I need to ignore the $.post callback function in here (but I would pick up func2 as a whole):

function func2()
{
$.post('myURL', {data: mydata}, function(data){
   // ignore me
   }
}

Obviously I need to identify the text: "function" (unless it's in a string literal for some reason) and I'm assuming I need to keep track of curly braces {} but otherwise, any ideas welcomed!

Many thanks for any suggestions! (Happy to use a PHP lib, 3rd party software or whatever)

Alex Kerr
  • 956
  • 15
  • 44
  • 1
    By definition, you're parsing the JS code. You're rummaging around in the string of the JS code to identify things. Even if it's not a full-blown JS-code parser, it's still a parser. – Marc B May 26 '16 at 14:01
  • 1
    *"I don't need to parse the code..."* Yes, you do. :-) Like [HTML](http://stackoverflow.com/a/1732454/157247), you cannot parse JavaScript code without...parsing it. Therefore, probably a duplicate of http://stackoverflow.com/questions/1554100/parsing-javascript-not-json-in-php. Also, a search for "php javascript parser" on A Famous Web Search Engine turned up several options. – T.J. Crowder May 26 '16 at 14:01
  • Thanks both. OK, technically, I'm parsing the code ;-) What I mean is, I don't want to get into the whole fulscale parsing and tokenisation game here, it's complete engineering overkill. All I basically need to do is identify the beginning of a function (easy, search string for "function") and then identify the closing bracket of the function (tricky and the bit I need help with) and ignore callback functions defined in the middle of other function definitions (also tricky and need help with). This is more of a string parsing situation I think. Continued... – Alex Kerr May 27 '16 at 12:47
  • ... I'm thinking of something along the lines of the code here: http://stackoverflow.com/a/5699775/4059141 but to identify functions rather than arrays. I have searched for solutions but they lead to full scale Javascript parsers which is much too complicated for my needs (including time to learn how to get what I want from them). Thanks for your input. – Alex Kerr May 27 '16 at 12:48

0 Answers0