【问题标题】:Get number from a string after specific character and convert that number从特定字符后的字符串中获取数字并转换该数字
【发布时间】:2017-05-25 22:03:35
【问题描述】:

我需要 regex php 方面的帮助。 如果在字符串中找到某个字符后的数字。获取该数字并在应用数学后将其替换为。像货币转换一样。

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

([^\?])澳元 (\d)

正则表达式不正确我想要所有匹配的数字,只有它匹配 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?你的正则表达式正确吗?
  • 到底是什么问题?
  • @WiktorStribiżew 没有正则表达式不正确我想要所有匹配的数字在这里只有匹配 40 但也有 20.00、9.95 等。我试图得到所有。并转换它们。
  • 如果你需要全部,你可以使用AUD ([\d.]+)之类的东西。这也将包括点.。并且您希望preg_match_all() 获得所有匹配项。

标签: php regex preg-replace preg-match preg-match-all


【解决方案1】:

如果您只需要获取所有这些值并使用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]));

this PHP demo

模式详情

  • \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 demo

【讨论】:

  • 我根据你的建议使用了 preg_replace_callback 。它对我有用。谢谢。
猜你喜欢
  • 1970-01-01
  • 2020-01-05
  • 2014-10-03
  • 1970-01-01
  • 2022-08-10
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多