I have string as below
$data = 1hs: "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 '.'
The code below should first fetch a number formatted as < number>[.< number>], and then take everything after that as a second group which should match your description unless there are some special cases not visible in your question.
preg_match('/([0-9]+\.{0,1}[0-9]*)\s+(.*?)/', $data, $matches);
print_r($matches);
This can be done in one line with string functions assuming the format is always the same
$string = '1hs: "1 U.S. dollar", rhs: "29.892653 Taiwan dollars"';
$data = explode(' ', trim(substr($string, strrpos($string, ':')+2), '"'),2);
var_dump($data);
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: