Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a string of words and double quoted currency amounts separated by commas and colons

I have string as below

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

I want to split the string with only spaces and double quotes so that I can get the array like this:

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

so far I use the code below

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

but it returns only the 29 and split all marks including '.'

like image 449
jeanpch Avatar asked Dec 19 '25 20:12

jeanpch


1 Answers

This regex will pull everything out for you into nicely named array fields.

$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 />";
}

Outputs:

  • Matched this: 1hs: "1 U.S. dollar"
  • Prefix: 1hs
  • Amount: 1
  • Type: U.S. dollar

And:

  • Matched this: rhs: "29.892653 Taiwan dollars"
  • Prefix: rhs
  • Amount: 29.892653
  • Type: Taiwan dollars
like image 64
methai Avatar answered Dec 21 '25 11:12

methai