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


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

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

Is this the fastest way?

3/6/2009 5:03:46 PM

Accepted Answer

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;
7/29/2014 10:52:27 PM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow