我試圖使用正則表達式在給定頁面上獲取價格,但用於存儲獲取內容的變量始終爲空。有人能幫我寫出正確的正則表達式嗎?在php中使用正則表達式從html頁面獲取數據
我想從這裏獲取價格260。
頁的標籤爲一些HTML代碼:
<span id="fk-mprod-our-id" class="price final-price our fksk-our">Rs.<span class="small-font"> </span>260</span>
我試圖使用正則表達式在給定頁面上獲取價格,但用於存儲獲取內容的變量始終爲空。有人能幫我寫出正確的正則表達式嗎?在php中使用正則表達式從html頁面獲取數據
我想從這裏獲取價格260。
頁的標籤爲一些HTML代碼:
<span id="fk-mprod-our-id" class="price final-price our fksk-our">Rs.<span class="small-font"> </span>260</span>
看起來這是使用final-price
類唯一的一次,所以這應該工作:
/final-price.+?>(\d+)</
假設貨幣可能會改變取決於知識產權/國家,我會使用爆炸(我並不擅長於Regex)
//consider that $html contains the page source
$html = explode('<span class="price final-price our fksk-our" id="fk-mprod-our-id">', $html);
$html = explode("</span>', $html[1]);
$price = $html[1];
我希望有所幫助。
你可以使用simplehtmldom編寫更多的防彈解析器 - 請參閱http://simplehtmldom.sourceforge.net/。對我來說,它永遠不會解析文檔。
您將結束這樣的代碼
<?php
include_once '/path/to/simplehtmldom/simple_html_dom.php';
$html = file_get_html('http://www.flipkart.com/mobiles/memory-cards/itmczcsrtvjeb6nr?pid=acccrrqzzsgnfgea&_l=sXQjsX87GxqrvKzhjuOrkw--&_r=n_2yuAC4xgh0SZTuulvAtw--&ref=af8ad0c4-62a2-4381-99d3-3ad8285e260b');
foreach ($html->find('span.final-price') as $element) {
echo $element->plaintext;
}
//will output "Rs. 260", unless page changes
更清潔的代碼,雖然它比正則表達式
時的表現噩夢