2013-06-25 45 views
1

我是新手到php得到兩個結果不重複preg_match和file_get_contents

而且我需要從同一頁得到兩個結果。 OG:圖片和og:視頻

這是我當前的代碼

preg_match('/property="og:video" content="(.*?)"/', file_get_contents($url), $matchesVideo); 
preg_match('/property="og:image" content="(.*?)"/', file_get_contents($url), $matchesThumb); 

$videoID = ($matchesVideo[1]) ? $matchesVideo[1] : false; 
$videoThumb = ($matchesThumb[1]) ? $matchesThumb[1] : false; 

有沒有重複我的代碼

+1

當然,將file_get_contents的結果分配給一個變量。 – datasage

+0

但你必須做兩次preg_match,因爲它不是相同的操作。但是,做'$ content = file_get_contents($ url);'會節省很多次 –

回答

1

有具有這兩條線沒有問題,執行相同的操作方式。我會改變的是對file_get_contents($url)的雙重打擊。

只是將其更改爲:

$html = file_get_contents($url); 
preg_match('/property="og:video" content="(.*?)"/', $html, $matchesVideo); 
preg_match('/property="og:image" content="(.*?)"/', $html, $matchesThumb); 
-1

有沒有重複我的代碼

總是有兩種方法可以做到這一點,執行相同的操作方式:

  1. 緩衝執行結果 - 而不是多次執行。
  2. 編碼重複 - 從代碼中提取參數。

在編程中,您通常使用兩者。例如,文件I/O操作的緩衝:

$buffer = file_get_contents($url); 

而對於匹配,你編碼重複:

$match = function ($what) use ($buffer) { 
    $pattern = sprintf('/property="og:%s" content="(.*?)"/', $what); 
    $result = preg_match($pattern, $buffer, $matches); 
    return $result ? $matches[1] : NULL; 
} 

$match('video'); 
$match('image'); 

這僅僅是示範性展示了我的意思。這取決於你想要做什麼,例如後者允許使用不同的實現來替換匹配,比如使用HTML解析器,但您可能會發現代碼太多,無法執行緩衝操作。

E.g.以下內容也可以適用:

$buffer = file_get_contents($url); 
$mask = '/property="og:%s" content="(.*?)"/'; 
preg_match(sprintf($mask, 'video'), $buffer, $matchesVideo); 
preg_match(sprintf($mask, 'image'), $buffer, $matchesThumb); 

希望這會有所幫助。

2

文件內容保存到一個變量,如果你想運行一個正則表達式,你可以選擇:

$file = file_get_contents($url); 
preg_match_all('/property="og:(?P<type>video|image)" content="(?P<content>.*?)"/', $file, $matches, PREG_SET_ORDER); 

foreach ($matches as $match) { 
    $match['type'] ... 
    $match['content'] ... 
} 

由於@hakre指出,不需要第一個括號對:

第一括號對使用無捕獲改性劑?:,它會導致匹配項,但是沒有存儲

捕獲組使用名爲子模式?P<name>的第二捕獲組建立任意兩個詞是可能的匹配image|video

+0

第一個(不匹配的)括號對對我來說看起來是多餘的。無論如何,組0將匹配,子組仍然會匹配。這只是沒有必要的,所以你可以專注於解釋被定義的子模式,而不是首先討論一個不需要的非匹配組; – hakre

+0

我不這麼認爲,不同'type'的標籤可能匹配模式 –

+0

不,只有整個模式可以匹配。這是視頻或圖像,沒有其他類型。組0是內在的,你不需要明確地創建它(總是整個模式,理想情況下使用()作爲外部括號而不是//)。試試看。 – hakre