doufei8250 2017-01-12 17:55
浏览 143
已采纳

在PHP中检查字符串中特定字符数量的最快方法是什么?

So i need to check if amount of chars from specific set in a string is higher than some number, what a fastest way to do that?

For example i have a long string "some text & some text & some text + a lot more + a lot more ... etc." and i need to check if there r more than 3 of next symbols: [&,.,+]. So when i encounter 4th occurrence of one of these chars i just need to return false, and stop the loop. So i think to create a simple function like that. But i wonder is there any native method in php to do such a thing? But i need some function which will not waste time parsing the string till the end, cuz the string may be pretty long. So i think regexp and functions like count_chars r not suited for that kind of job...

Any suggestions?

  • 写回答

3条回答 默认 最新

  • 普通网友 2017-01-12 19:31
    关注

    Well, all my thoughts were wrong and my expectations were crushed by real tests. RegExp seems to work from 2 to 7 times faster (with different strings) than self-made function with simple symbol-checking loop.

    The code:

    // self-made function:
    function chk_occurs($str,$chrs,$limit){
        $r=false;
        $count = 0;
        $length = strlen($str);
        for($i=0; $i<$length; $i++){
            if(in_array($str[$i], $chrs)){
                $count++;
                if($count>$limit){
                    $r=true;
                    break;
                }
            }
        }
        return $r;
    }
    
    // RegExp i've used for tests:
    preg_match('/([&\\.\\+]|[&\\.\\+][^&\\.\\+]+?){3,}?/',$str);
    

    Of course it works faster because it's a single call to native function, but even same code wrapped into function works from 2 to ~4.8 times faster.

    //RegExp wrapped into the function:
    function chk_occurs_preg($str,$chrs,$limit){
        $chrs=preg_quote($chrs);
        return preg_match('/(['.$chrs.']|['.$chrs.'][^'.$chrs.']+?){'.$limit.',}?/',$str);
    }
    

    P.S. i wasn't bothered to check cpu-time, just was testing walltime measured via microtime(true); of the 200k iteration loop, but it's enough for me.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?