Piyush Kumar Baliyan
Piyush Kumar Baliyan

Reputation: 404

Regex for retrieving jquery functions from html file not working on PHP server

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?

Upvotes: 0

Views: 72

Answers (1)

Alex
Alex

Reputation: 17289

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 :-)

Upvotes: 1

Related Questions