Reputation: 47
I have an associative array from which I extract two numbers with regular expression
<?php
$link = array (
"model_one" => "Only 50.95 usd for 2 years or 700.30 usd.",
"model_two" => "Only 70.95 usd for 2 years or 900.20 usd.");
foreach ($link as $key=>$links) {
$pattern = '/.\d+(?:\.\d{2})?((?<=[0-9])(?= usd))/';
preg_match_all($pattern,$links,$result);
$final = array();
foreach($result[0] as $k=>$v) {
$final[]=$v;
echo $final[0]; // print 50.95 50.95 70.95 70.95
}
}
?>
I was not able to retrieve every single number associated to key
Example:
model_one 50.95
model_one 700.30
model_two 70.95
model_two 900.20
Upvotes: 0
Views: 1970
Reputation: 76636
You need to loop through the array containing matched values:
foreach ($link as $key => $links) {
$pattern = '/\d+(?:\.\d{2})?((?<=[0-9])(?= usd))/';
preg_match_all($pattern,$links,$result);
foreach ($result[0] as $amt) {
echo "$key $amt\n";
}
}
Note that I've also removed the period character (.
) from the beginning of your regular expression. It will match any character that's not a space. This will cause the capture to contain a space at the beginning.
Output:
model_one 50.95
model_one 700.30
model_two 70.95
model_two 900.20
Upvotes: 2