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

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

    What Assaf said is correct. There is a built in function in PHP to do exactly that.

    substr_compare($str, $test, strlen($str)-strlen($test), strlen($test)) === 0;
    

    If $test is longer than $str PHP will give a warning, so you need to check for that first.

    function endswith($string, $test) {
        $strlen = strlen($string);
        $testlen = strlen($test);
        if ($testlen > $strlen) return false;
        return substr_compare($string, $test, $strlen - $testlen, $testlen) === 0;
    }
    

提交回复
热议问题