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

Lem*_*azi 5 php regex preg-replace preg-match-all preg-match

我需要一个正则表达式php的帮助.如果在字符串中找到某个字符后的数字.获取该数字并在应用数学后替换它.像货币转换.

我应用了这个正则表达式https://regex101.com/r/KhoaKU/1

([^ \?] )AUD(\ d)

正则表达式不正确我希望所有匹配的数字在这里只有它匹配40但是还有20.00,9.9等..我想要得到所有.并转换它们.

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);
}
Run Code Online (Sandbox Code Playgroud)

Wik*_*żew 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]));
Run Code Online (Sandbox Code Playgroud)

请参阅此 PHP 演示

图案详情

  • \b- 前导词边界
  • AUD- 文字字符序列
  • - 空间
  • (\d*\.?\d+)- 第 1 组捕获 0+ 数字,可选的.,然后捕获 1+ 数字。

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

如果您想更改输入文本中的这些值,我建议在 a 中使用相同的正则表达式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;
Run Code Online (Sandbox Code Playgroud)

查看PHP 演示