2011-03-28 121 views
1

我做了這個代碼:問題的foreach循環

$matches = array(); 
preg_match_all('/"Type":".+?",/', $text, $matches); 


foreach($matches[0] as $match) { 
    if (isset($_GET['dvd']) && !empty($_GET['dvd'])) { 
     $dvd = $_GET['dvd']; 
     if (stripos($match, 'DVD') !== false) { 
      $match = ''; 
     } 
    } 
    echo $match; 
} 

在這段代碼中我搜索在$字文「類型」,並在它前面存儲的話整條生產線在數組中。然後我遍歷每一個,看看是否有字DVD。如果是,則刪除它並顯示一個空白行。


現在我還想搜索假設製造商並將其顯示在返回的每種類型下。

所以應該返回假設結果:

Type: HDD 
Manufacturer: WD 

Type: Flash Drive 
Manufacturer: Transcend 

Type: CD 
Manufacturer: Sony 

所以我把另一preg_match_all表達試了一下:

$anotherMatch = array(); 
preg_match_all('/"Manufacturer":".+?",/', $text, $anotherMatch); 

,我想這與以前的foreach表達與& &結合操作員,但它沒有工作。此外,我嘗試了不同的foreach表達式,然後在最後回顯一個。但這也沒有奏效。

你能告訴我如何達到預期的效果。謝謝...

+0

你有沒有機會提供你試圖從中獲取信息的文本的例子? – 2011-03-28 15:30:51

+0

該文本將是沒有任何HTML的格式化文本,並且只有一個搜索和回顯,一切正常。但我想添加兩個,因爲我可以一起打印。 – 2011-03-28 15:34:44

+0

我們需要一個例子,如果我們應該知道如何得到這兩個正則表達式將起作用。 – 2011-03-28 15:36:00

回答

0

鑑於源輸入這樣的:

"Type":"HDD", 
"Manufacturer":"WD", 
"Other":"Nonsense", 
"Type":"Flash Drive", 
"Manufacturer":"Transcend", 
"Other":"More nonsense", 
"Type":"CD", 
"Manufacturer":"Sony", 
"Other":"Yet even more nonsense", 

,並期望輸出是這樣的:

Type: HDD 
Manufacturer: WD 

Type: Flash Drive 
Manufacturer: Transcend 

Type: CD 
Manufacturer: Sony 

您可以使用正則表達式:

/"(Type|Manufacturer)":"([^"]+?)",/ 

和環如下:

preg_match_all('/"(Type|Manufacturer)":"([^"]+?)",/', $text, $matches); 

foreach($matches[0] as $match => $line) 
{ 
    if (!empty($_GET['dvd']) && stripos($matches[2], 'DVD') !== false) 
    { 
     continue; 
    } 
    echo $matches[1][$match] . ': ' . $matches[2][$match] . "\n"; 
} 

雖然,我不認爲這將完全符合您的要求。