Reputation: 41
I have a file which has jquery codes into the head section, like following..
<head>
<script>
$(document).ready(function(){
$('.x').click(function(){
// some thing
});
$('.y').click(function(){
// some thing
});
});
</script>
</head>
I want to use PHP to read the file and retrieve the content that are located inside the $(document).ready(function(){
section by using regular expression like preg_match_all
. More specifically saying I need the two .click
functions. Purpose is academic only. Any help will be appreciated.
Upvotes: 0
Views: 189
Reputation: 3200
What about something like this?
\$\((?!document\).ready).*?\}\);
Here's what this expression does:
\$\(
- This looks for a literal dollar sign $
followed by an opening parenthesis (
.(?!document\).ready)
- This is a negative lookahead that says document).ready
cannot be following the $(
..*?
- The dot .
allows any character to be matched, the asterisk *
allows that character to be matched any number of times and the question mark ?
makes it ungreedy and tells it to stop matching when it hits the next part of the expression. The closing brackets.\}\);
- This final part is simply the closing tags. It's going to use a literal closing curly brace }
, followed by a closing parenthesis )
and a semicolon ;
to be the end of the string.Of course, since you are matching so many REGEX reserved characters, we end up with five slashes.
Anyway, if you take that an put it into a preg_match_all
context, you'd end up with something like this:
preg_match_all('~\$\((?!document\).ready).*?\}\);~sim', $string, $matches);
print "<pre>"; print_r($matches[0]); print "</pre>";
This outputs:
Array
(
[0] => $('.x').click(function(){
// some thing
});
[1] => $('.y').click(function(){
// some thing
});
)
Here is a working demo. http://ideone.com/R1t5P5
Upvotes: 1
Reputation: 752
See this regex:
<head>\s*<script> # Anchor your regex to these tags
\s*\$\(\h*document\h*\)\.ready\( # Match the beginning statement
([\S\s]+) # Grab the content you want
\);\s* # Match the ending statement
<\/script> # Anchor the last closing tag to prevent over-matching
So, everything you want is inside the first capture group. This is a dirty way of getting your content, but based on your aforementioned assurances of no varying content, this should work fine.
Upvotes: 0