用于页面抓取的正则表达式

时间:2012-02-20 17:45:31

标签: php regex

我正在尝试编写一个页面抓取脚本来获取网站的货币。我需要一些帮助来编写正则表达式。

这是我到目前为止所拥有的。

<?php

function converter(){
       // Create DOM from URL or file
       $html = file_get_contents("http://www.bloomberg.com/personal-    finance/calculators/currency-converter/");

    // Find currencies. ( using h1 to test)
        preg_match('/<h1>(.*)<\/h1>/i', $html, $title);
        $title_out = $title[1];
        echo $title_out;

}

 $foo = converter();
 echo $foo;



?>

以下是Bloomberg网站上保存货币的地方。

网站:http://www.bloomberg.com/personal-finance/calculators/currency-converter/

//<![CDATA[
      var test_obj = new Object();
      var price = new Object();
                price['ADP:CUR'] = 125.376;

获得该费率的表达方式是什么样的? 任何帮助都会很棒!!

3 个答案:

答案 0 :(得分:3)

这对我有用 - 它需要更灵活吗?是否需要采取各种空白 - 或者它总是只有一个空间? (在等号周围)

"/price\['ADP:CUR'\] = (\d+\.\d+/)"

用法:

if(preg_match("/price\['ADP:CUR'\] = (\d+\.\d+)/", $YOUR_HTML, $m)) {
//Result is in $m[1]
} else {
//Not found
}

答案 1 :(得分:3)

你去吧:

/ADP:CUR[^=]*=\s*(.*?);/i

答案 2 :(得分:2)

这将返回一个与bloomberg站点上的javascript对象相同的关联数组。

<?php
$data = file_get_contents('http://www.bloomberg.com/personal-finance/calculators/currency-converter/');

$expression = '/price\\[\'(.*?)\'\\]\\s+=\\s+([+-]?\\d*\\.\\d+)(?![-+0-9\\.]);/';

preg_match_all($expression, $data, $matches);

$array = array_combine($matches[1], $matches[2]);

print_r($array);

echo $array['ADP:CUR'];// string(7) "125.376"
?>