我有这样的字符串。
$50 From here i need only 50
$60.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.
换句话说,我需要从字符串的开头删除所有货币标签,我只需要第一笔金额。 希望我的问题很明确。 感谢
答案 0 :(得分:2)
答案 1 :(得分:1)
我建议不要使用正则表达式,因为它对这种情况来说太过分了。
$str = (int)ltrim($str, '$£€');
这就是你所需要的一切。
我通过脚本运行上述测试,看看我的答案与使用RegEx之间的时差是多少,平均而言RegEx解决方案的速度慢了约20%。
<?php
function funcA($a) {
echo (int)ltrim($a, '$£€');
};
function funcB($a) {
echo preg_replace('/^.*?([0-9]+).*$/', '$1', $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
答案 2 :(得分:0)
你可以去:
<?php
$string = <<<DATA
$50 From here i need only 50
$60.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
)
)
*/
?>
答案 3 :(得分:0)
答案 4 :(得分:0)
以下方式使用
$str = '$50 From here i need only 50
$60.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);
答案 5 :(得分:0)
$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
有你需要的东西。