2013-04-04 58 views
0

試圖獲得一個「參考代碼」,從HTML,但僅僅是「裁判」,當標籤爲PPHP的preg_match我如何

例:031-0132-806-02

哪有我這樣做使用preg_match?

如何通過preg_match獲取此信息?

{ 
label: 'P', 
available: false, 
ref: '031-0132-806-02' 
}, 
{ 
label: 'M', 
available: false, 
ref: '031-0132-806-03' 
}] 
} 
}, 
+3

爲什麼不'json_decode()',然後再處理對象/數組得到你想要的信息數據進行解碼? – Sammitch 2013-04-04 17:50:55

+0

該代碼是一個對象還是你想正確的代碼? – 2013-04-04 17:50:56

+0

是的...那裏有一個JSON裏面的HTML。它以productPage1.init開頭({和用//完成]]> \t。有沒有辦法使用preg_math? – adrianogf 2013-04-04 17:58:27

回答

0

使用foreach循環:

$string = <<<WUT 
{ 
label: 'P', 
available: false, 
ref: '031-0132-806-02' 
}, 
{ 
label: 'M', 
available: false, 
ref: '031-0132-806-03' 
}] 
} 
}, 
WUT; 

$ref = array(); 

preg_match_all('/(?P<labels>{\s*label:.*?})/s', $string, $m); 

foreach($m['labels'] as $code){ 
    if(strpos($code, "label: 'P'")){ 
     preg_match('/ref: \'(.*?)\'/', $code, $n); 
     $ref[] = $n[1]; 
    } 
} 

print_r($ref); 
2

如果數字總是以相同的模式,你可以用這個做到這一點:

<?php 
    $string = "{ 
    label: 'P', 
    available: false, 
    ref: '031-0132-806-02' 
    }, 
    { 
    label: 'M', 
    available: false, 
    ref: '031-0132-806-03' 
    }] 
    } 
    },"; 

    preg_match_all('![0-9]{3}\-[0-9]{4}\-[0-9]{3}\-[0-9]{2}!',$string,$matches); 

    print_r($matches); 

?> 

更新比方說,這是對數據的履帶。

<?php 

$url = 'http://www.urltocapture...'; 

function crawlSite($url){ 
    $refIDs = array(); 
     $string = file_get_contents($url); 

     preg_match_all('!\items: +?\[[^]]+\]!s',$string,$sets); 
     foreach($sets as $items){ 
      foreach($items as $item){ 

       $cleanupPattern = array('!\t+!','! +!','!(\r\n|\n|\r)+!','! +!'); 
       $cleanupReplacements = array(' ',' ',""," ",); 
       $item = preg_replace($cleanupPattern,$cleanupReplacements,$item); 
       //echo $item."\n";  

      preg_match_all('!label: \'P\'[^\}]+([0-9]{3}\-[0-9]{4}\-[0-9]{3}\-[0-9]{2})[^\}]+}!',$item,$item_match); 

       if(!empty($item_match[1][0])){ 
        $refIDs[] = $item_match[1][0]; 
       } 
      } 
     } 
     return $refIDs; 

} 

$refIDs = crawlSite($url); 
print_r($refIDs); 

?> 
+0

好的..不過,我怎樣才能得到「ref」當「標籤」是「P」?這個字符串是在html內部的json的一部分。有一種方法可以得到json使用preg_match並使用json_decode()?URL引用是www.netshoes.com.br/produto/031-0132-172-02 – adrianogf 2013-04-04 18:09:28

+0

這是您的網站(訪問原始json)還是您正在挖掘它? – 2013-04-04 18:22:20