Trim 货币字符串中的符号和小数值

Trim symbol and decimal value from currency string

我有这样的货币输入字符串。

换句话说,我需要从字符串的开头删除所有货币符号,我只需要整数值 -- 小数值可以被截断。

这个正则表达式应该可以做到

($|€|£)\d+

这更好(感谢 Jan)

[$€£]\d+

与 PHP 的 Preg Match

一起使用

preg_match — Perform a regular expression match

你可以选择:

<?php

$string = <<<DATA
 From here i need only 50
.59 From here i need only 60, Need to remove $ and .59
€360 From here i need only 360.
€36.99 From here i need only 36 need to remove € and .99.
£900 From here i need only 900.
£90.99 From here i need only 90.
DATA;

# look for one of $,€,£ followed by digits
$regex = '~[$€£]\K\d+~';

preg_match_all($regex, $string, $amounts);
print_r($amounts);
/*
Array
(
    [0] => Array
        (
            [0] => 50
            [1] => 60
            [2] => 360
            [3] => 36
            [4] => 900
            [5] => 90
        )

)
*/

?>

a demo on ideone.com

使用正则表达式。例如:

$toStr = preg_replace('/^.*?([0-9]+).*$/', '', $fromStr);

请参阅 preg_replace 文档。

使用以下方式

    $str = ' From here i need only 50
    .59 From here i need only 60, Need to remove $ and .59
    €360 From here i need only 360.
    €36.99 From here i need only 36 need to remove € and .99.
    £900 From here i need only 900.
    £90.99 From here i need only 90.';

    $arr_ = array('$','€','£');

    echo str_replace($arr_,'',$str);
$newString=$string;
$currencyArray = array("$","€","£"); //just add the new item if you want that to add more
foreach($currencyArray  as $value) 
  $newString= str_replace($value,"",$newString);   

$newString有你需要的。

我建议不要使用正则表达式,因为它对这种情况来说太过分了。

$str = (int)ltrim($str, '$£€');

这就是您所需要的。


性能与正则表达式

我 运行 通过脚本进行上述测试,以查看我的答案与使用 RegEx 之间的时间差,平均而言,RegEx 解决方案慢了约 20%。

<?php
function funcA($a) {
    echo (int)ltrim($a, '$£€');
};
function funcB($a) {
    echo preg_replace('/^.*?([0-9]+).*$/', '', $a);
};
//setup (only run once):
function changeDataA() {}
function changeDataB() {}

$loops = 50000;
$timeA = 0.0;
$timeB = 0.0;
$prefix =  str_split('€$€');

ob_start();
for($i=0; $i<$loops; ++$i) {
    $a = $prefix[rand(0,2)] . rand(1,999) . '.' . rand(10,99);

    $start = microtime(1);
    funcA($a);
    $timeA += microtime(1) - $start;

    $start = microtime(1);
    funcB($a);
    $timeB += microtime(1) - $start;
}
ob_end_clean();

$timeA = round(1000000 * ($timeA / $loops), 3);
$timeB = round(1000000 * ($timeB / $loops), 3);

echo "
TimeA averaged $timeA microseconds
TimeB averaged $timeB microseconds
";

时间因系统负载而异,因此应仅考虑彼此之间的时间,而不是在执行之间进行比较。此外,这不是性能基准测试的完美脚本,有可能影响这些结果的外部影响,但这给出了一个总体思路。

TimeA averaged 5.976 microseconds
TimeB averaged 6.831 microseconds