2013-07-26 32 views
0

所以我今天正在學習正則表達式和東西,我得到它的工作方式,我想如何,但是當我試圖把它作爲一個東西從一個網站獲取數據的一部分使用時,它不行。有趣的是,如果我回應我正在檢索的原始HTML,然後將其作爲手動字符串放入正則表達式,它工作正常。有誰知道爲什麼會發生? 下面是代碼:正則表達式不工作返回值

preg_match_all('/<img src="images\/cms\/trinket\/(.*).png" \/><\/a> 
       <div style="width:85px; font-size:14px; font-weight:bold; 
       color:#731c08;">(.*)<\/div>/iU', snd('test.php'), 
       $matches, PREG_SET_ORDER); 

SND是捲曲返回,這可能是造成問題的原因,但我不知道數據的功能。

SND功能:

function snd($url) { 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, 'http://whatever.com/'.$url); 
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1468.0 Safari/537.36'); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_HEADER, 1); 
    $result = curl_exec($ch); 
    curl_close($ch); 

    return $result; 
} 

例(添加了可讀性換行符):

<div style="width:600px; margin-left:auto; margin-right:auto; text-align:center; position:relative; z-index:1;"> 
<span style="display:inline-block; width:85px; height:100px;"> 
<a rel="includes/itemajax.php?id=789&tab=trinket" class="clue"> 
<img src="images/cms/trinket/789.png" /></a> 
<div style="width:85px; font-size:14px; font-weight:bold; color:#731c08;">4</div> 
</span> <span style="display:inline-block; width:85px; height:100px;"> 
<a rel="includes/itemajax.php?id=891&tab=trinket" class="clue"> 
<img src="images/cms/trinket/891.png" /></a> 
<div style="width:85px; font-size:14px; font-weight:bold; color:#731c08;">3</div> </span>  

應該返回:789,4和891,3

+4

雖然 @DarkBee雖然 – DarkBee

+0

颳了一個網站u'r更好但我甚至不知道如何搜索這樣的模式使用一個 – lemondrop

+0

如果您懷疑問題是與snd函數的返回值那麼請張貼該代碼。 –

回答

1

比較後您的示例文本的正則表達式,看起來問題在於「空白」樣本文本本身。

例如,img src=不匹配,但如果將其更改爲img[\s]+src=,則會。

如果添加在您的正則表達式這種變化,你應該結束了:

<img[\s]+src="images\/cms\/trinket\/(.*).png"[\s]+\/><\/a>[\s\r\n]+<div[\s]+style="[^"]+">(.*)<\/div> 

如果要拆分模式到多行的可讀性,你也可以使用x標誌爲「忽略模式空白「:

preg_match_all('/<img[\s]+src="images\/cms\/trinket\/(.*).png"[\s]+\/><\/a>[\s\r\n]+ 
       <div[\s]+style="[^"]+">(.*)<\/div> 
       /iUx', 
       snd('test.php'), $matches, PREG_SET_ORDER); 

注:我也更新div的屬性style值的列表只是[^"]+因爲完整列表是相當長的和不必要的;如果需要,您可以隨時將其添加回來。

+0

我的良善它的工作。非常感謝。 – lemondrop