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 '.'
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:
And:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With