正则表达式 - PHP

时间:2013-06-04 05:36:33

标签: php regex preg-match preg-match-all

我正在使用以下PHP代码

<?
    $data = file_get_contents('http://www.kitco.com/texten/texten.html');
    preg_match_all('/([A-Z]{3,5}\s+[0-9]{1,2},[0-9]{4}\s+([0-9.NA]{2,10}\s+){1,7})/si',$data,$result);

    $records = array();
    foreach($result[1] as $date) {
        $temp = preg_split('/\s+/',$date);
        $index = array_shift($temp);
        $index.= array_shift($temp);
        $records[$index] = implode(',',$temp);
    }
    print_R($records);
?>

阅读以下数据

  --------------------------------------------------------------------------------
   London Fix          GOLD          SILVER       PLATINUM           PALLADIUM
                   AM       PM                  AM       PM         AM       PM
   --------------------------------------------------------------------------------
   Jun 03,2013   1396.75   1402.50   22.4300   1466.00   1487.00   749.00   755.00  
   May 31,2013   1410.25   1394.50   22.5700   1471.00   1459.00   755.00   744.00  
   --------------------------------------------------------------------------------

我想要做的是从下表中读取GOLD(BID&amp; ASK)价格,任何人都可以帮助改变正则表达式吗?

纽约现货价格                 市场已经关闭             将在

中打开
----------------------------------------------------------------------
   Metals          Bid        Ask           Change        Low       High 
   ----------------------------------------------------------------------
   Gold         1411.20     1412.20    +22.90  +1.65%    1390.10  1418.00 
   Silver         22.74       22.84     +0.48  +2.13%      22.26    23.08 
   Platinum     1495.00     1501.00    +41.00  +2.82%    1470.00  1511.00 
   Palladium     756.00      761.00     +7.00  +0.93%     750.00   766.00 
   ----------------------------------------------------------------------
   Last Update on Jun 03, 2013 at 17:14.58
   ----------------------------------------------------------------------

3 个答案:

答案 0 :(得分:2)

我不确定您是否可以修改现有的正则表达式以轻松匹配两个表,但如果您在字符串中有第二个表,则可以使用:

$string = "PLAIN TEXT TABLE DATA HERE";

preg_match('/Gold\s+(\d+\.\d{2})\s+(\d+\.\d{2})/',$string,$matches);

$goldBid = $matches[1];
$goldAsk = $matches[2];

答案 1 :(得分:1)

这里我只匹配数字和句点字符。此代码应返回您要查找的数字。它使用您示例中的数据字符串。

<?
preg_match_all('!Gold\s+([0-9.]+)\s+([0-9.]+)!i',$data,$matches);

//New York
$ny_bid = $matches[1][0];
$ny_ask = $matches[2][0];
print("NY\nbid: $ny_bid\n");
print("ask: $ny_ask\n\n");

//Asia
$asia_bid = $matches[1][1];
$asia_ask = $matches[2][1];
print("Asia\nbid: $asia_bid\n");
print("ask: $asia_ask\n");
?>

<强>输出

NY
bid: 1411.20
ask: 1412.20

Asia
bid: 1406.80
ask: 1407.80

答案 2 :(得分:0)

您也可以使用T-Regx library

<?php
pattern('Gold\s+([0-9.]+)\s+([0-9.]+)', 'i')->match($data)->forEach(function ($m) {
    print 'bid: ' . $m->group(1);
    print 'ask: ' . $m->group(2);
});