从特定字符后面的字符串中获取数字并将该数字转换

5
我需要协助处理 PHP 正则表达式。如果在字符串中找到某个字符后面的数字,请获取该数字并在应用数学运算后进行替换,例如货币转换。
我使用了这个正则表达式 https://regex101.com/r/KhoaKU/1 ,但它不正确。我想要匹配所有数字,而不仅仅是 40,因为还有 20.00、9.95 等等。我正在尝试获取所有这些数字并将其进行转换。
function simpleConvert($from,$to,$amount)
{
    $content = file_get_contents('https://www.google.com/finance/converter?a='.$amount.'&from='.$from.'&to='.$to);

     $doc = new DOMDocument;
     @$doc->loadHTML($content);
     $xpath = new DOMXpath($doc);

     $result = $xpath->query('//*[@id="currency_converter_result"]/span')->item(0)->nodeValue;
     return $result;
}

$pattern_new = '/([^\?]*)AUD (\d*)/';
if ( preg_match ($pattern_new, $content) )
{
    $has_matches = preg_match($pattern_new, $content);
    print_r($has_matches);
   echo simpleConvert("AUD","USD",$has_matches);
}

所以,你要匹配的值是 40 吗?你的正则表达式正确吗? - Wiktor Stribiżew
问题到底是什么? - jeroen
@WiktorStribiżew 正则表达式不正确,我想要所有匹配的数字,这里只匹配了40,但还有20.00、9.95等等。我正在尝试获取并转换它们。 - Lemon Kazi
1
如果你需要全部内容,可以使用类似于 AUD ([\d.]+) 的东西。这将包括点 .。并且你想要使用 preg_match_all() 来获取所有匹配项。 - jeroen
1个回答

3

如果你只需要获取所有这些值并使用 simpleConvert 进行转换,那么可以使用一个正则表达式来匹配整数/浮点数,并在获取到这些值后将数组传递给 array_map

$pattern_new = '/\bAUD (\d*\.?\d+)/';
preg_match_all($pattern_new, $content, $vals);
print_r(array_map(function ($a) { return simpleConvert("AUD", "USD", $a); }, $vals[1]));

请看此PHP演示模式细节:
  • \b - 单词边界
  • AUD - 字符序列
  • - 空格
  • (\d*\.?\d+) - 第1组匹配0个或多个数字,一个可选的 . 和 1个以上的数字。

请注意,传递给simpleConvert函数的$m [1]保存了第一个(也是唯一的)捕获组的内容。

如果您想更改输入文本中的这些值,建议在preg_replace_callback中使用相同的正则表达式:

$content = "The following fees and deposits are charged by the property at time of service, check-in, or check-out.\r\n\r\nBreakfast fee: between AUD 9.95 and AUD 20.00 per person (approximately)\r\nFee for in-room wireless Internet: AUD 0.00 per night (rates may vary)\r\nFee for in-room high-speed Internet (wired): AUD 9.95 per night (rates may vary)\r\nFee for high-speed Internet (wired) in public areas: AUD 9.95 per night (rates may vary)\r\nLate check-out fee: AUD 40\r\nRollaway beds are available for an additional fee\r\nOnsite credit card charges are subject to a surcharge\r\nThe above list may not be comprehensive. Fees and deposits may not include tax and are subject to change.";
$pattern_new = '/\bAUD (\d*\.?\d+)/';
$res = preg_replace_callback($pattern_new, function($m) {
    return simpleConvert("AUD","USD",$m[1]);
}, $content);
echo $res;

请查看PHP演示

1
我按照你的建议使用了 preg_replace_callback。它对我很有效。谢谢。 - Lemon Kazi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接