正则表达式在 PHP 中提取 JavaScript 变量 [英] Regular expression extract a JavaScript variable in PHP

查看:27
本文介绍了正则表达式在 PHP 中提取 JavaScript 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的 HTML 文件,其中包含很多内容.例如,我想从整个文件中获取一个名为 'a' 的 JavaScript 变量.

I have a large HTML file, containing a lot of content. I want to get a JavaScript variable, named 'a' for example, from the whole file.

示例:(删除了大量实际内容)

Example: (deleted lots of the actual content)

<html>
    <head>
        <script>
            var a = [{'a': 1, 'b': 2}];
        </script>
    </head>
    <body>
        ....
    </body>
</html>

从上面应该得出的是:

[{'a': 1, 'b': 2}]

推荐答案

preg_match('#var a = (.*?);\s*$#m', $html, $matches);
echo $matches[1];

说明:

  • Regex 将尝试匹配任何包含 var a =
  • 的行
  • 然后它将匹配所有内容,直到 ;、任意数量的空格 \s*,然后是行尾 $
  • m 修饰符将尝试独立匹配每一行,没有它,$ 只会匹配字符串的结尾,这有点无用
  • Regex will try to match any line containing var a =
  • It will then match everything up until a ;, any amount of spaces \s*, then the end of the line $
  • The m modifier will try to match each line independently, without it, the $ would just match then end of the string which would be a bit useless

任意数量的空格仅在定义后有一些空格时才存在,没有其他原因(例如人为错误).如果您确定不会发生这种情况,您可以删除 \s*.

The any amount of spaces is only there in case you have some spaces after the definition, no other reason (e.g. human error). If you're sure that won't happen, you can remove \s*.

请注意,这不会取代成熟的解析器.如果 a 定义在多行上,则需要进行修改,如果 a 定义不止一次(考虑范围,您可以将 var a 在全局范围内,然后在函数内使用 var a),等等.

Note that this doesn't replace a full-blown parser. You will need to make modifications if a is defined over more than one line, if a is defined more than once (think about scope, you can have var a on a global scope, then var a within a function), etc.

这篇关于正则表达式在 PHP 中提取 JavaScript 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆