我的字符串如下
$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并拆分所有标记,包括'。'
答案 0 :(得分: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 />";
}
输出:
和
答案 1 :(得分:0)
下面的代码应首先获取格式为&lt;的数字。数&GT;并[d数字&gt;],然后将其后的所有内容作为第二组,除非您的问题中没有显示某些特殊情况,否则应与您的描述相符。
preg_match('/([0-9]+\.{0,1}[0-9]*)\s+(.*?)/', $data, $matches);
print_r($matches);
答案 2 :(得分:0)
这可以在一行中使用字符串函数来完成,假设格式始终相同
$string = '1hs: "1 U.S. dollar", rhs: "29.892653 Taiwan dollars"';
$data = explode(' ', trim(substr($string, strrpos($string, ':')+2), '"'),2);
var_dump($data);