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

后端 未结 13 751
时光说笑
时光说笑 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:17

    This method is a tiny bit more memory-expensive, but it is faster:

    stripos(strrev($haystack), $reversed_needle) === 0;
    

    This is best when you know exactly what the needle is, so you can hard-code it reversed. If you reverse the needle programatically, it becomes slower than the earlier method.

提交回复
热议问题