3

我正在使用以下 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 和 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
   ----------------------------------------------------------------------
4

3 回答 3

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];
于 2013-06-04T05:42:56.490 回答
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
于 2013-06-04T06:40:01.050 回答
0

您还可以使用T-Regx 库

<?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);
});
于 2019-05-27T16:02:11.963 回答