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

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

    This is pure PHP, without calling external functions, except for strlen.

    function endsWith ($ends, $string)
    {
        $strLength = strlen ($string);
        $endsLength = strlen ($ends);
        for ($i = 0; $i < $endsLength; $i++)
        {
            if ($string [$strLength - $i - 1] !== $ends [$i])
                return false;
        }
        return true;
    }
    

提交回复
热议问题