2011-12-31 30 views
0

我试图使用正则表达式在给定页面上获取价格,但用于存储获取内容的变量始终为空。有人能帮我写出正确的正则表达式吗?在php中使用正则表达式从html页面获取数据

如果页面:http://www.flipkart.com/mobiles/memory-cards/itmczcsrtvjeb6nr?pid=acccrrqzzsgnfgea&_l=sXQjsX87GxqrvKzhjuOrkw--&_r=n_2yuAC4xgh0SZTuulvAtw--&ref=af8ad0c4-62a2-4381-99d3-3ad8285e260b

我想从这里获取价格260。

页的标签为一些HTML代码:

<span id="fk-mprod-our-id" class="price final-price our fksk-our">Rs.<span class="small-font"> </span>260</span> 

回答

0

看起来这是使用final-price类唯一的一次,所以这应该工作:

/final-price.+?>(\d+)</ 
0

假设货币可能会改变取决于知识产权/国家,我会使用爆炸(我并不擅长于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]; 

我希望有所帮助。

2

你可以使用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 

更清洁的代码,虽然它比正则表达式

时的表现噩梦