javascript - 使用 PHP 和 REGEX 解析 JS 脚本以获取 JS 变量值

标签 javascript php regex json proxmox

我需要从 PHP 打开一个 JS 文件,在该文件中找到一个 json 变量,并将其转换为 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);
}

关于javascript - 使用 PHP 和 REGEX 解析 JS 脚本以获取 JS 变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28719680/

相关文章:

javascript - react-router 如何使用 redirectLocation 或 301 或 302 状态

javascript - 对象键(不是值)上的 d3.extent()

javascript - foreach 具有多个函数异步

php - 如何使用 php 向 paypal 汇款

Javascript 与 C++ 通信

javascript - Jquery 欧芹验证不起作用

php - 如何存储数据直到恢复 android 设备的连接然后添加到 mysql 数据库?

python - 确定字符串是否不能是有效正则表达式的简单方法

javascript - 使用正则表达式的 JavaScript 中的有效电子邮件地址

php - 在 mySQL 正则表达式中使用多个值