parse javascript text with php
Greetings! I have heard of various methods to capture and return text. For example regular expressions. I am slightly ne开发者_如何转开发w to PHP but I was wondering how I would capture and return text from this JavaScript code using PHP. I am only interested in capturing msgBody, msgTitle, and insertDate. Thank you for looking my my problem
function wibiyaNotifierLoad() {
if (typeof(jQuery.cookie) == 'function') {
loadjscssfile("Graphics_Toolbar/Notifier/notifier_2.css?v2", "css", "head");
var data = {
"count": 1,
"notifications": [{
"Id": "264727",
"toolbarId": "602582",
"msgId": "9",
"msgTitle": "Its that time of year!",
"msgBody": "check you email for updates!",
"msgLink": "",
"msgImage": "",
"filter": "",
"startDate": "2011-03-22 23:00:00",
"expirationDate": "2011-03-23 00:00:00",
"active": "1",
"insertDate": "2011-03-22 23:12:31"
}],
"ok": true
};
When you say parsing, you should look into J4P5. But you can probably get away with an inexact solution and regular expressions here. To capture the text and then extract individual values:
preg_match('#(\[\{.*?\}\])#s', $javascript, $match);
$values = json_decode($match[1], TRUE);
$msgBody = $values[0]["msgBody"];
Could make the regex more explicit by starting it with '#"notifications": (\[\{
however.
For a single regex to capture the data you need, you could use the following pattern (note that this needs backslashes and quotes to the escaped when inserted into code):
/(["'])(msgBody|msgTitle|insertDate)\1\s*:\s*(['"])((?:[^'"\\]+|\\.|(?!\3|\\).)*)\3/s
The name of the key will be in the sub capture 2 and the actual content in the sub capture 4. For example, let's assume your javascript is stored in $text
, you could use the following PHP code to extract the information:
<?php
$regex = '/(["\'])(msgBody|msgTitle|insertDate)\\1\\s*:\\s*([\'"])((?:[^\'"\\\\]+|\\\\.|(?!\\3|\\\\).)*)\\3/s';
preg_match_all($regex, $text, $match, PREG_SET_ORDER);
$data = array();
foreach ($match as $cap)
{
$data[$cap[2]] = $cap[4];
}
var_dump($data);
preg_match('/\[(.*?)\]/s', $javascript, $match);
$json = json_decode($match[1]);
print $json->{'msgBody'};
print $json->{'msgTitle'};
print $json->{'insertDate'};
I often use the preg_replace function to capture some data that I want. You can try it out here:
http://www.functions-online.com/preg_replace.html
This website provides tools that you can use to hone your regular expression skills
http://gskinner.com/RegExr/
精彩评论