如何仅获取美元符号后面的数字

3

如果$str是这样的sokewe(letter) $ 10,00 seqee(letter),如何仅获取美元符号后面的数字?

例如:sokewe(letter) $ 10,00 seqee(letter) sokewe(letter) $ 1000 seqee(letter)

<?php

if (preg_match('/\$\s[0-9]/',$str)) {
  // echo'has $ digit';
  $currency = '$';
  $digit = ..
} else if (preg_match('/\$[0-9]/',$str)) {
  // echo'has $digit';
  $currency = '$';
}

if (preg_match('/\£\s[0-9]/',$str)) {
  // echo'has £ digit';
  $currency = '£';
} else if (preg_match('/\£[0-9]/',$str)) {
  // echo'has £digit';
  $currency = '£';
}

if (preg_match('/\€\s[0-9]/',$str)) {
  // echo'has € digit';
  $currency = '€';
} else if (preg_match('/\€[0-9]/',$str)) {
  // echo'has €digit';
  $currency = '€';
}

你想在输出中显示 10 还是 10,00 - anubhava
他说数字,所以可能只是1。 - user557846
如果有使用逗号,则我想要10,00。 - user1775888
作为一个附注,考虑在\s?中使用?量词。 - njzk2
你甚至可以在另一组中捕获货币!/([$€£])\s?([0-9])/ - njzk2
显示剩余2条评论
5个回答

3

您可以使用:

if (preg_match('/\$\D*(\d+(?:,\d+)*)/', $input, $matches)) {
   echo $matches[1] . "\n"; // 10,00
}

正则表达式演示


我尝试添加分组,像这样'/([$£€])\D*(\d+(?:,\d+)*)/',我做错了什么吗? - user1775888
1
这个也应该可以工作:http://regex101.com/r/dL7oK9/2,请确保现在使用匹配组#2,即`$matches [2]`。 - anubhava

1

捕获它:

if (preg_match('/\$\s([0-9])/',$str, $matches)) {
                     ^-----^       ^^^^^^^^^^
   $digit = $matches[1];
}

0

嗨,你只需要使用PHP正则表达式

$str = '$10.00';
preg_match('/\d+(,|.)?\d+/',$str,$matches);


print_r($matches);

您也可以进行测试。以防万一,我使用了逗号 (,) 和句点 (.) ,因为您可能有 $、€、£ 符号,并且金额可能用句点或逗号表示。

如果您想进行测试,可以使用以下链接 http://leaverou.github.io/regexplained/


0

试试这个:

if(preg_match('/([£$€])([0-9]+[.,]?(?:[0-9]{2})?)/', $str, $matches)) {
    $currency = $matches[1];
    $value = $matches[2];
}

-1

示例。 您可以使用 substr 和 strrchr。

$string = '$ 10,00';

$return = substr(strrchr($string, '$'), 1);

echo $return; //10,00


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