如何按空格分割字符串以及php中的双引号

问题描述 投票:0回答:4

我有如下字符串

$data = 1hs: "1 U.S. dollar", rhs: "29.892653 Taiwan dollars"

我想只用空格和双引号分割字符串,这样我就可以得到这样的数组:

$data[ ]= 29.892653  <--- the most important part I would like to get. 
$data[ ]= Taiwan dollars <--- not sure is it possible to do this?

到目前为止我使用下面的代码

$data = preg_split("/[,\s]*[^\w\s]+[\s]*/", $data,0,PREG_SPLIT_NO_EMPTY); 

但它只返回 29 并分割所有标记,包括“.”

php
4个回答
1
投票

这个正则表达式将为您将所有内容提取到命名良好的数组字段中。

$data = '1hs: "1 U.S. dollar", rhs: "29.892653 Taiwan dollars"';

// Using named capturing groups for easier reference in the code
preg_match_all(
    '/(?P<prefix>[^,\s:]*):\s"(?P<amount>[0-9]+\.?[0-9]*)\s(?P<type>[^"]*)"/', 
    $data, 
    $matches, 
    PREG_SET_ORDER);

foreach($matches as $match) {
    // This is the full matching string
    echo "Matched this: " . $match[0] . "<br />";

    // These are the friendly named pieces
    echo 'Prefix: ' . $match['prefix'] . "<br />";
    echo 'Amount: ' . $match['amount'] . "<br />";
    echo 'Type: ' . $match['type'] . "<br />";
}

输出:

  • 匹配此:1hs:“1 美元”
  • 前缀:1hs
  • 数量:1个
  • 类型:美元

并且:

  • 匹配此:rhs:“29.892653 新台币”
  • 前缀:rhs
  • 金额:29.892653
  • 种类:台币

0
投票

下面的代码应首先获取格式为 < number>[.< number>] 的数字,然后将其后的所有内容作为第二组,该组应与您的描述相匹配,除非您的问题中存在一些不可见的特殊情况。

preg_match('/([0-9]+\.{0,1}[0-9]*)\s+(.*?)/', $data, $matches);
print_r($matches);

0
投票

这可以使用字符串函数在一行中完成,假设格式始终相同

$string = '1hs: "1 U.S. dollar", rhs: "29.892653 Taiwan dollars"';
$data = explode(' ', trim(substr($string, strrpos($string, ':')+2), '"'),2);
var_dump($data);

0
投票

该输入字符串的格式看起来非常可预测,并且由于需要提取数字,因此您可以使用

sscanf()
进行解析,将数字转换为浮点数 (
%f
) 或整数 (
%d
)。

代码:(演示

$data = 'lhs: "1 U.S. dollar", rhs: "29.892653 Taiwan dollars"';

var_export(
    sscanf(
        $data,
        'lhs: "%f %[^"]", rhs: "%f %[^"]"'
    )
);

输出:

array (
  0 => 1.0,
  1 => 'U.S. dollar',
  2 => 29.892653,
  3 => 'Taiwan dollars',
)

如果有任何通配符应该从返回的数组中省略,就像百分号后面的星号一样。 演示

© www.soinside.com 2019 - 2024. All rights reserved.