如何从 js 文件中检索值

How to retrieve a value from js file?

本文关键字:检索 文件 js      更新时间:2023-09-26

基本上我的问题是你如何获取js文件中变量的值。

例如

var now = (new Date() - 0);
other_var = 'Whats up';//how to pull the value of the other_var which is 'Whats Up'
key.embed();

如何使用 php 获取other_var的值?我只需要变量的值,即"whats up"。

自己做了一些挖掘,现在我能够使用 php 中的file_get_content函数获取 js 文件的内容,只是不知道如何拉取变量并拉取其值。

<?php
  $file = file_get_contents('myfile.js');
  $varNameToFind = 'other_var';
  $expr = '/^'s*(?:var)?'s*'.$varNameToFind.''s*='s*([''"])(.*?)'1's*;?/m';
  if (preg_match($expr, $file, $matches)) {
    echo "I found it: $matches[2]";
  } else {
    echo "I couldn't find it";
  }

类似的东西?请注意,它只会在查找引号时找到字符串值,并且其中有各种漏洞,允许它匹配一些语法无效的 Javascript 内容,并且当字符串中有转义引号时它会下降 - 但只要 JS 有效,它应该找到文件中将字符串值分配给命名变量的第一个位置, 带或不带 var 关键字。

编辑

一个更好的版本,只匹配语法上有效的 Javascript 字符串,并且应该匹配任何有效的单个字符串,包括带有转义引号的字符串,尽管它仍然不会处理连接表达式。它还获取字符串的实际值,就像加载到 Javascript 中时一样 - 即它插入此处定义的转义序列。

只需查找"other_var = ",然后检查它之后的内容...获取文件

$content = file_get_contents(...);

如果我假设文件内容如您所描述的:

    var now = (new Date() - 0);
other_var = 'Whats up';//how to pull the value of the other_var which is 'Whats Up'
key.embed();

那么我可以建议您使用以下方法:

    $data = file_get_contents("javascriptfile.js"); //read the file
//create array separate by new line
//this is the part where you need to know how to navigate the file contents 
//if your lucky enough, it may be structured statement-by-statement on each
$contents = explode("'n", $data); 
$interestvar = "other_var";
$interestvalue = "";
foreach ($contents as $linevalue)  
{
    //what we are looking for is :: other_var = 'Whats up';
    //so if "other_var" can be found in a line, then get its value from right side of the "=" sign
    //mind you it could be in any of the formats 'other_var=xxxxxx', 'other_var= xxxxxx', 'other_var =xxxxxx', 'other_var = xxxxxx', 
    if(strpos($linevalue,$interestvar." =")!==false){
        //cut from '=' to ';'
        //print strpos($linevalue,";");
        $start = strpos($linevalue,"=");
        $end = strpos($linevalue,";");
        //print "start ".$start ." end: ".$end;
        $interestvalue = substr($linevalue,$start,$end-$start);
        //print $interestvalue;
        break;
    }
}
if($interestvalue!=="")
print "found: ".$interestvar. " of value : ".$interestvalue;