普通的前pression提取PHP中的JavaScript变量 [英] Regular expression extract a JavaScript variable in PHP
问题描述
我有一个大的HTML文件,包含了很多内容。我希望得到一个JavaScript变量,名为'A'
为例,从整个文件。
例如:(删除大量的实际内容)
< HTML和GT;
< HEAD>
<脚本>
变种一个= [{'一个':1,'B':2}];
< / SCRIPT>
< /头>
<身体GT;
....
< /身体GT;
< / HTML>
我应该来自上面是:
[{'A':1,'B':2}]
preg_match('#VAR一个=(*);?\\ S * $#M', $ HTML,$匹配);
回声$比赛[1];
说明:
- 正则表达式将尝试匹配任何包含行
VAR一个=
- 。然后会匹配一切,直到一个
;
,空格任何金额\\ s *
,然后结束行$
- 的
M
修改将尝试每一行单独匹配,没有它,$
将只匹配,则结束这将是一个有点用处的字符串
的空格任何金额的仅仅是存在的情况下,你有一些空间的定义,没有其它原因(例如人为错误)之后。如果你确信不会发生,你可以删除 \\ S *
。
请注意,这并不能取代一个全面的解析。您将需要进行修改,如果 A
被定义在多个行,如果 A
定义不止一次(想想范围,你可以有 VAR一个
在全球范围内,那么 VAR一个
在函数中)等。
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>
What should come from the above is:
[{'a': 1, 'b': 2}]
preg_match('#var a = (.*?);\s*$#m', $html, $matches);
echo $matches[1];
Explanation:
- 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
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*
.
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.
这篇关于普通的前pression提取PHP中的JavaScript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!