duan010167787 2016-08-10 13:09
浏览 96
已采纳

从字符串php中删除一些字符

I have strings like this.

$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.

In Other word i need to remove all currency tag from the start of the string and i need only first amount. Hope my question is clear. Thanks

  • 写回答

6条回答 默认 最新

  • douzhan1238 2016-08-10 14:51
    关注

    I would recommend not using a regular expression, as it's overkill for this scenario.

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

    this is all you need.


    Performance vs Regex

    I ran the above test through a script to see what the time difference is between my answer and using a RegEx, and on average the RegEx solution was ~20% slower.

    <?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
    ";
    

    Timings vary depending on system load, so times should be considered only relative to each other, not compared between executions. Also this isn't a perfect script for performance benchmarking, there are outside influences that can affect these results, but this gives a general idea.

    TimeA averaged 5.976 microseconds
    TimeB averaged 6.831 microseconds
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等