我有一个关联数组,我从中提取两个带正则表达式的数字
<?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
}
}
?>
我无法检索与密钥
关联的每个号码示例:
model_one 50.95
model_one 700.30
model_two 70.95
model_two 900.20
答案 0 :(得分:2)
您需要遍历包含匹配值的数组:
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";
}
}
请注意,我还从正则表达式的开头删除了句点字符(.
)。它将匹配任何不是空格的角色。这将导致捕获在开头包含空格。
输出:
model_one 50.95
model_one 700.30
model_two 70.95
model_two 900.20