1

我想从数组中获取一些值并将它们打印在页面上。

对于 [1],应提取以下内容:USD 7.0269 6.4119 0.14231 0.15596

数组如下所示:

print_r($arr);
[1] => USD United States of America 7.0269  6.4119  Dollars 0.14231 0.15596  � Copyright 2003-2011. Powered by CurrencyXchanger 3.580 
[2] => EUR  Euro Member Countries 9.0373    8.3253  Euro    0.1107  0.1201   � Copyright 2003-2011. Powered by CurrencyXchanger 3.580

实现这一目标的最佳解决方案是什么?

4

5 回答 5

1

这是一个正则表达式解决方案:

foreach($arr as $key => $item)
{
    preg_match('/^([A-Z]){3}[\sA-Za-z]+(\d+\.\d+)\s+(\d+\.\d+)\s+[A-Za-z]+\s+(\d+\.\d+)\s+(\d+\.\d+)/', $item, $matches);
    $result[$key] = array_shift($matches);
}

正则表达式对应于您的模式,并在$matches. 由于$matches[0]代表完全匹配,我们删除第一个元素并将其分配给您的结果数组。

于 2012-10-24T13:31:38.233 回答
1

preg_match_all()在我修剪掉感兴趣的区域后我会使用:

foreach ($arr as $line) {
    // currency is in the first four characters (apparently)
    $currency = substr($line, 0, 4);

    // we use everything left of 'Copyright'
    $rest = strstr($line, 'Copyright', true);

    // match each occurrence of nn.nnnn
    if (preg_match_all('/\d+\.\d+/', $rest, $matches)) {
        // $matches[0] contains all the amounts
        echo $currency, ' ', join(' ', $matches[0]), PHP_EOL;
    }
}

对于 PHP < 5.2,您需要此行来计算$rest

$rest = substr($line, 0, strpos($line, 'Copyright'));

演示

于 2012-10-24T13:32:13.277 回答
0

尝试

 foreach($arr as $v) {
  $items = explode(' ', $v);
  $new_arr[] = $items[0]; //Getting the currency type
  foreach($items as $k => $m) {
    if(is_numeric($m) && floor($m) != $m && $k != (count($items) - 1))
      $new_arr[] = $m;
  }
 }

 //displaying the $new_arr
 foreach($new_arr as $n) {      
  if(is_numeric($n) === FALSE)
    echo "\n";     
    echo $n . ' ';
 }

在此处查看实际操作

于 2012-10-24T13:27:58.990 回答
0

使用正则表达式,您可以获得它。

foreach($arr as $key => $value) {
    preg_match_all('/(\d+\.\d+)/', $value, $matches);
    $result[substr($value, 0, 3)] = array_shift($matches);
}

你得到一个这样的数组

var_dump($result);
array (
    'USD' => array( 7.0269, 6.4119, 0.14231,  0.15596 )
    'EUR' => array( 9.0373, 8.3253, 0.1107,  0.1201 )
)
于 2012-10-24T13:42:16.177 回答
0

快速完成:

$result = array_map(
    function ($string) {
        preg_match_all('/(\d+\.\d+)\s/', $string, $matches);
        return substr($string, 0, 3) . ' ' . implode(' ', $matches[1]);
    },
    $arr
);

结果:

Array
(
    [0] => USD 7.0269 6.4119 0.14231 0.15596
    [1] => EUR 9.0373 8.3253 0.1107 0.1201
)
于 2012-10-24T13:56:08.163 回答