2011-06-10 85 views
1

我有幾個字符串已從另一個網站使用cURL提取。該字符串包含整個頁面的HTML結構,但每一個頁面裏面有概述如下段落:PHP - 從字符串中提取值

<p>Displaying 1-15 of 15 items beginning with A</p>
<p>Displaying 1-20 of 33 items beginning with B</p>

我需要做的只是從這些字符串中提取的總價值(15在上述情況下爲33)。

我不確定提取值的最佳方法是什麼。

謝謝:)

+2

我敢打賭,有人會很快提供一個答案,使用正則表達式來提取總數 – andyb 2011-06-10 12:57:44

+1

哦,真的嗎?我剛剛做到了。 :) – 2011-06-10 12:58:46

+0

@Tomasz赫赫,感謝您驗證我的理論:-) +1爲你。 – andyb 2011-06-10 13:03:05

回答

5

創建一個正則表達式;

$regex = "/Displaying 1-([0-9]+) of ([0-9]+) items begginning with/"; 
preg_match($regex,$resultfromcurl,$match); 

是這樣的嗎?

+1

非常感謝你,+1 – lethalMango 2011-06-10 13:12:32

1

可能會遲到一天,但是這裏是我的2美分:這將解析文件中的html,抓取段落,找到匹配,並將所有相關值放入數組中使用。

<?php 

// Open your document 
$doc = new DOMDocument(); 

// Parse the HTML 
$doc->loadHTMLFile("html_doc.html"); 

// Find the paragraphs and loop through them 
$paras = $doc->getElementsByTagName('p'); 

// Initialize value array 
$range = array(); 

// Extract the value and put them in a useful data structure 
for ($i = 0; $i < $paras->length; $i++) { 
    $subject = $paras->item($i)->nodeValue; 
    preg_match('/Displaying (\d+)-(\d+) of (\d+) items beginning with ([A-Z]+)/', $subject, $matches); 
    $range[$matches[4]] = array(
     'start' => $matches[1], 
     'stop' => $matches[2], 
     'total' => $matches[3] 
    ); 
} 

foreach ($range as $begin => $values) { 
    echo "\n$begin\n"; 
    echo "start: " . $values['start'] . "\n"; 
    echo "stop: " . $values['stop'] . "\n"; 
    echo "total: " . $values['total'] . "\n"; 
    echo "------\n"; 
}