Search code examples
phpjavascriptzend-view

Searching for a javascript function definition within a string using PHP?


I'm using Zend_View_Helper_HeadScript to display javascript function definitions in the head of my webpages, and I extended it to get the javascript code from file if desired. What I'd like to know is if there would be an easy way to search the headScript output (basically, a series of xhtml script elements) for a javascript function definition, assuming I got and outputted the contents of javascript files (rather than including the srcs.) I mean, I could search for "function" followed by some function name characters and then "(" but that doesn't account for possible comments in the code. Is there a quickie function for this that is built into PHP that can search for a javascript function definition? Or something else prebuilt?

Sample output:

<script type="text/javascript">

// function testMe() {}

function otherTest() {alert('Just testing!');}

/*

function testMe() {}

*/

</script>

Obviously testMe() hasn't really been defined here...

For clarity, I'm trying to do something like this:

<?php

$htmlScriptElements = $view->headScript()->toString();
$functionName = 'testMe';

$file = '/path/to/testMe.js';
$type = 'text/javascript';
$attrs = array();
$getScript = TRUE;

if (!js_function_definition_found($functionName, $htmlScriptElements)) {

    $view->headScript()->appendFile($file, $type, $attrs, $getScript);

}

The headScript helper is home-brew; if $getScript is true, I use file_get_contents() to get the js content and append that instead of including a js file using a url/src. I realize that it won't find definitions in included js files; I'm fine with that.


Solution

  • I'm going to make a guess here and say what you are wanting is a PHP based Parser/Lexer for Javascript. You may want to take a look at the Spidermonkey PECL extension as it may get you part way there.