What's the most efficient test of whether a PHP string ends with another string?

后端 未结 13 750
时光说笑
时光说笑 2020-11-29 18:53

The standard PHP way to test whether a string $str ends with a substring $test is:

$endsWith = substr( $str, -strlen( $test ) ) ==          


        
13条回答
  •  [愿得一人]
    2020-11-29 19:14

    It depends on which sort of efficiency you care about.

    Your version uses more memory due to the extra copy from the use of substr.

    An alternative version might search the original string for the last occurrence of the substring without making a copy, but would probably be slower due to more testing.

    Probably the most efficient way is to do loop char-by-char from the -sterlen(test) position till the end of the string and compare. That's the minimal amount of comparisons you can hope to do and there's hardly any extra memory used.

提交回复
热议问题