PHP正则表达式匹配动态变量名的JavaScript对象
PHP正则表达式匹配动态变量名的JavaScript对象
以下代码展示如何使用PHP正则表达式匹配动态变量名的JavaScript对象。
$html = '<script type="text/javascript">var player_aaaa = {"flag":"play","encrypt":0,"trysee":0,"points":0,"link":"\/vodplay\/339927-1-1.html","link_next":"","link_pre":"","vod_data":{"vod_name":"\u9053\u58eb\u964d\u9b542\u4e4b\u50f5\u5c38\u6751","vod_actor":"\u6768\u6613\u4e4b,\u9648\u8bd7\u5609,\u8fb0\u8f69\u9510","vod_director":"\u6768\u6613\u4e4b","vod_class":"\u6050\u6016,\u5267\u60c5"},"url":"https:\/\/vip.lz-cdn7.com\/20230118\/13580_14fd770e\/index.m3u8","url_next":"","from":"lzm3u8","server":"no","note":"","id":"339927","sid":1,"nid":1};</script><script type="text/javascript" src="/static/js/playerconfig.js?t=20230527"></script><script type="text/javascript" src="/static/js/player.js?t=a20230527"></script>';
preg_match('/var\s+(\w+)\s*=\s*(.*?);/', $html, $match);
if(isset($match[1])) {
$player_data = json_decode($match[1], true);
// 输出所有键值内容
print_r($player_data);
}
解释:
var\s+(\w+)\s*=\s*(.*?);是正则表达式,用于匹配JavaScript对象。var匹配关键字var。\s+匹配一个或多个空格。(\w+)匹配变量名,并将其捕获到第一个分组中。\s*=\s*匹配等号,前后可能存在空格。(.*?)匹配JavaScript对象的内容,并将其捕获到第二个分组中。;匹配分号。
代码示例:
上述代码中,$match[1] 保存了匹配到的变量名,$match[2] 保存了JavaScript对象的内容。json_decode() 函数将JavaScript对象解析为PHP数组,然后可以通过 print_r() 函数输出。
注意:
- 正则表达式中的
\s+匹配一个或多个空格,如果变量名和等号之间没有空格,需要修改正则表达式以匹配这种情况。 - 如果JavaScript对象中包含特殊字符,例如单引号、双引号等,需要在正则表达式中进行转义。
- 如果JavaScript对象中存在嵌套对象或数组,需要使用递归方法解析。
总结:
本文介绍了如何使用PHP正则表达式匹配动态变量名的JavaScript对象,并提供代码示例和解释。通过使用正则表达式,可以方便地提取JavaScript对象的内容并进行解析。
原文地址: https://www.cveoy.top/t/topic/ojg8 著作权归作者所有。请勿转载和采集!