用于从html文件中检索jquery函数的正则表达式无法在PHP服务器上运行

用于从html文件中检索jquery函数的正则表达式无法在PHP服务器上运行

问题描述:

I am using regex code to find jquery functions used inside any html file. The php code is:

<?php
$file=<<<FOO
<html>
<body>
    <div class="content">
        <div class="main-content">
            <ul class="show-sport">
                <li class="active"><img src="assets/img/show-1.png"/></li>
                <li><img src="assets/img/show-2.png"/></li>
                <li><img src="assets/img/show-3.png"/></li>
            </ul>
        </div>
    <script>
        $('.show-sport').fadeSlider({speed:5000});
        $('.modal-switch').modal();
    </script>
    </div>
</body>
</html>
FOO;
preg_match_all("/\$\('(.*)'\).(.*)\((.*)\)/", $file, $jQuery_func);
var_dump($jQuery_func);
?>

The $file will store file contents later on. This is output I am getting:

array (size=4)
  0 => 
    array (size=0)
      empty
  1 => 
    array (size=0)
      empty
  2 => 
    array (size=0)
      empty
  3 => 
    array (size=0)
      empty

But when I am testing it on any other online php regex tester, it is giving:

Array
(
    [0] => Array
        (
            [0] => $('.show-sport').fadeSlider({speed:5000})
            [1] => $('.modal-switch').modal()
        )

    [1] => Array
        (
            [0] => .show-sport
            [1] => .modal-switch
        )

    [2] => Array
        (
            [0] => fadeSlider
            [1] => modal
        )

    [3] => Array
        (
            [0] => {speed:5000}
            [1] => 
        )
)

You can see the results here http://www.phpliveregex.com/p/9fo, click preg_match_all tab.

PHP version: 5.4.16 | Apache Version: 2.4.4

I have hit my head many times but can't set it working on localhost. Is there any PHP extension that needs to be enabled to get it working?

just made some debug

you have different regex in your php than on your online link page :-) (or I don't know why :-) it must be different)

so just change your regex pattern from:

preg_match_all("/\$\('(.*)'\).(.*)\((.*)\)/", $file, $jQuery_func);

to

preg_match_all("/\\$\('(.*)'\).(.*)\((.*)\)/", $file, $jQuery_func);

or

$pattern = "/\\$\('(.*)'\).(.*)\((.*)\)/";
                var_dump($pattern);
                    preg_match_all($pattern, $file, $jQuery_func);

to see why we should escape dollar sign twice

it works :-)