正则表达式刮板挑战

时间:2013-06-30 11:14:09

标签: php html regex

我正在构建一个php数据挖掘器(scrapper) 我有这个HTML行:

<label class='area'>
  <font class='bg_info' onmouseover="land_convert_txt(this,3067)" onmouseout='tooltip_hide()'>
   3,067 Sq. Ft.
  </font>

如何设置我的正则表达式只提取区域值?

这是我的功能:

function extract_regex($subject, $regex, $index = 1)
{
    preg_match_all($regex, $subject, $matches);
    if (count($matches[$index]))
    {
        if (count($matches[$index]) == 1)
        {
            return trim($matches[$index][0]);
        }
        return $matches[$index];        
    }
    return '';
}

(this,3067)不断变化!

先谢谢你

2 个答案:

答案 0 :(得分:1)

不要使用Regex处理HTML!
不要试图重新发明轮子,你可能会创建一个正方形。

尝试使用一些PHP网页抓取工具,例如:

http://net.tutsplus.com/tutorials/php/html-parsing-and-screen-scraping-with-the-simple-html-dom-library/

使用如下代码:

# create and load the HTML
include('simple_html_dom.php');
$html = new simple_html_dom();
$html->load($myHTML);

# get an element representing the area element
//$element =  $html->find('label[class=area]'); 
$element = $html->find(".area")

# Echo it out
echo $element[1]->innertext

答案 1 :(得分:0)

 function extract_regex($subject, $regex, $index = 1)
    {
        preg_match_all($regex, $subject, $matches);
        if (count($matches[$index]))
        {
            if (count($matches[$index]) == 1)
            {
                return trim($matches[$index][0]);
            }
            return $matches[$index];        
        }
        return '';
    }

    $out = extract_regex("<label class='area'><font class='bg_info' onmouseover='land_convert_txt(this,3067)' onmouseout='tooltip_hide()'>3,067 Sq. Ft.</font></label>","/<label class=\'area\'>(.*)<\/label>/i");

        echo "<xmp>". $out . "</xmp>";
相关问题