2016-06-13 18 views
1

我有一个完整的页面HTML报废,有很多标记包括HTML/CSS/JS代码。下面正则表达式从废弃的HTML提取Javascript对象

例(剥离量)

<p>blah blah blah html</p> 
<script type="text/javascript">window._userData ={"country_code": "PK", "language_code": "en",user:[{"user": {"username": "johndoe", "follows":12,"biography":"blah blah blah","feedback_score":99}}],"another_var":"another value"} </script> 
<script> //multiple script tags can be here... </script> 
<p>blah blah blah html</p> 

现在我要提取的对象中window._userData,然后,如果可能的转换所提取的字符串到PHP对象/阵列。

我已经尝试了一些在SO上找到的正则表达式,但无法正常工作。

我也试图在这里类似的答案Regular expression extract a JavaScript variable in PHP

感谢

+0

您想要提取的对象不正确。 – splash58

+0

@ splash58我添加了缺少的},感谢您的评论,请解决任何问题? – Alyas

+1

此外,它不能包含空格,并且必须包含引号中的所有键 - “{”country_code“:”PK“,”language_code“:”en“,”user“:[{”user“:{”username“:”johndoe “,”follow“:12,”biography“:”blah blah blah“,”feedback_score“:99}}],”another_var“:”另一个值“}' – splash58

回答

2

查找正则表达式

preg_match('/\bwindow\._userData\s*=(.+)(?=;|<\/script)/', $html, $m); 

和解码

json_decode(trim($m[1]), true); 

但是,你应该在正确的JSON之前HTML。

+0

这是正确的方法,但当脚本标记包含多个JS对象和/或者该对象包含带有';'的字符串。如果你能排除它会起作用。 编辑:JS不是一种常规语言[此答案适用](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) –

+1

@JohannesStadler如果json包含';'或EOL,它真的是一个问题,我不知道如何解决 – splash58

+0

我认为这是不可能的正则表达式。 Js不是常规语言,因此正则表达式有其局限性。 –