我需要从PHP打开一个JS文件,在这个文件中找到一个json var,并将其转换为php数组。
现在我无法弄清楚要使用哪个正则表达式。
// get the js file
$file = file_get_contents ("http://pve.proxmox.com/pve2-api-doc/apidoc.js");
// extract the json content of var pveapi
if ( preg_match ( "#pveapi = ({[^}]*})#", $file, $infoJson ) ) {
$arrJson = json_decode ( $infoJson [1], true );
}
// shows nothing so far :((
print_r($arrJson);
我找到的例子很少,但没有一个对我有用。任何在正则表达式方面具有良好技能的人都可以帮助我吗?
本
编辑:添加了JS文件的一部分:
var pveapi = [
{
"info" : {
"GET" : {
"parameters" : {
"additionalProperties" : 0
},
"permissions" : {
"user" : "all"
},
"returns" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {}
},
"links" : [
{
"rel" : "child",
"href" : "{name}"
}
]
},
"name" : "index",
"method" : "GET",
"description" : "Cluster index."
}
}
}
];
Ext.onReady(function() { ... }
在这种情况下,可以通过匹配行尾的分号来找到结尾:
if (preg_match('/^var pveapi = (.*?);$/ms', $js, $matches)) {
$data = json_decode($matches[1]);
print_r($data);
}
默认情况下,正则表达式引擎在各个行上贪婪地运行,所以你必须告诉它做相反的事情——你似乎正在寻找的正则表达式将是
#'spveapi's*='s*(.*?);'s*$#s
它的作用是:
#
开始表达式's
确保变量名称前面有空格,这样它就不是其他变量名称的一部分pveapi
查找变量's*='s*
确保周围有一个等号和可选的空格(.*?);'s*$
在找到分号之前获取尽可能少的字符 - 即所有字符直到第一个分号,后面只有可选的空格和行尾#ms
结束表达式并告诉它让.
也匹配行尾,并将$
与每行的结尾匹配