开发者

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

开发者 https://www.devze.com 2022-12-16 14:13 出处:网络
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 i

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 somet开发者_Python百科hing 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.


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.


You can test for the existence of a JavaScript function from JavaScript itself with the typeof operator, e.g.

typeof alert === 'function' // true
typeof foo   === 'function' // false

or, if you are not interested in the type, you can do

if (window.alert) { ... }

where window is the scope of the function you are looking for, e.g. document.getElementById or myModule.someFn

So you don't have to check from PHP. If you would want to do this from PHP, you could iterate over the headscript placeholder and parse the strings inside. I am not aware of a function that would do findAllJavaScripts(), so it would require some clever Regex.

0

精彩评论

暂无评论...
验证码 换一张
取 消