Which is more efficient, PHP string functions or regex in PHP?

后端 未结 9 1846
甜味超标
甜味超标 2020-12-06 16:48

I\'m writing PHP code to parse a string. It needs to be as fast as possible, so are regular expressions the way to go? I have a hunch that PHP string functions are more expe

相关标签:
9条回答
  • 2020-12-06 17:31

    If what you're doing is at all reasonable to do using string functions, you should use them. Like, if you're determining whether a constant string 'abc' occurs in $value, you definitely want to check strpos($value, 'abc') !== false, not preg_match('/abc/', $value). If you find yourself doing a lot of string reshuffling and transformations in order to accomplish what you would've with a regex, though, you're almost certainly going to wind up destroying both performance and maintainability.

    When concerned about speed, though, when it comes down to it, don't think about it, clock it. The time command is your friend.

    0 讨论(0)
  • 2020-12-06 17:33

    It depends on your case: if you're trying to do something fairly basic (eg: search for a string, replace a substring with something else), then the regular string functions are the way to go. If you want to do something more complicated (eg: search for IP addresses), then the Regex functions are definitely a better choice.

    I haven't profiled regexes so I can't say that they'll be faster at runtime, but I can tell you that the extra time spent hacking together the equivalent using the basic functions wouldn't be worth it.


    Edit with the new information in the OP:

    It sounds as though you actually need to do a number of small string operations here. Since each one individually is quite basic, and I doubt you'd be able to do all those steps (or even a couple of those steps) at one time using a regex, I'd go with the basic functions:

    Grab the first half (based on the third location of a substring "000000") and compare its hash to the next 20 bytes, throwing away anything left.

    Use: strpos() and substr()
    Or : /$(.*?0{6}.*?0{6}.*?)0{6}/

    Then grab the next 19 bytes after that, and split that into 8 (toss 1) and 8.

    Use: substr() - (I assume you mean 17 bytes here -- 8 + 1 + 8)

    $part1 = substr($myStr, $currPos, 8);
    $part2 = substr($myStr, $currPos + 9, 8);
    
    0 讨论(0)
  • 2020-12-06 17:34

    Native string functions are way faster. The benefit of regexp is that you can do pretty much anything with them.

    0 讨论(0)
提交回复
热议问题