0

基本上我的问题是如何在 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();

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

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

4

3 回答 3

1

只需查找“other_var =”,然后检查它后面的内容......获取文件

$content = file_get_contents(...);
于 2012-06-08T10:10:29.857 回答
1
<?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 时一样 - 即,它插入此处定义的转义序列。

于 2012-06-08T10:17:45.910 回答
1

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

    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;
于 2012-06-08T10:24:23.013 回答