下面的代碼可以在採集其它網站的數據時,取得JS裏某個變量的值。針對下兩種JS的寫法,利用兩個不同的正則先取到JS部分的代碼,然後再在代碼裏取需要的變量。
<script>function test(){}</script>
<script type="text/javascript">function test(){}</script>
php代碼:
<?php
$str = '<script>function test(){}</script><script type="text/javascript">function aa(){ '.
'var enDtime=xxx;}</script><div><div> <div class="foo bar">ok</div></div></div>';
$patten="'var endtime=(.*?);'is";
echo getVarInjs($str,$patten);
function getVarInjs($str,$patten,$withType = true)
{
$patten_js = $withType?"'<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>'is":"'<\s*script\s*>(.*?)<\s*/\s*script\s*>'is";
preg_match_all($patten_js, $str, $matches);
foreach($matches[1] as $m)
{
//過濾取值
preg_match($patten,$m,$result);
if(!empty($result[1]))
return $result[1];
}
return false;
}
顯示結果:
xxx