2016-06-13 89 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不是常規語言,因此正則表達式有其侷限性。 –