从PHP Array获取特定值

时间:2012-10-24 13:23:47

标签: php regex arrays

我想从数组中获取一些值并在页面上打印出来。

对于[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

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

5 个答案:

答案 0 :(得分: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]表示完全匹配,因此我们删除第一个元素并将其分配给结果数组。

答案 1 :(得分: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'));

Demo

答案 2 :(得分: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 . ' ';
 }

在行动here

中查看

答案 3 :(得分: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 )
)

答案 4 :(得分: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
)