How to determine if a string ends with a particular string in PHP?

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Unfortunately, there is no built-in PHP function that tests if a “haystack” string ends with a “needle” string. As an concrete example, suppose you want to determine if the string (known as the haystack) “automation test” ends with the string “test” (known as the needle). We are looking for a needle in the haystack.

Let’s write a function which we’ll call “endsWith” which will take two parameters, the first being the string to look in (the haystack), and the second being the string we are looking for (the needle). Function will return true if and only if the needle is found and is at the very end of the haystack string.

This problem with be easy if we were looking at the start of the string and use the strpos, or the case-insensitivity version stripos. So we will reverse the two string and use stripos. Yes, PHP has a strrev function that does string reversal.

So we construction our function as follows…

function endsWith($haystack, $needle) {
        if ( strpos(strrev($haystack), strrev($needle) ) === 0 ) {
            return true;
        } else {
            return false;
        }
}

We are using the case-sensitive comparison. If you want case-insensitive comparison, use stripos instead as in …

function endsiWith($haystack, $needle) {
        if ( stripos(strrev($haystack), strrev($needle) ) === 0 ) {
            return true;
        } else {
            return false;
        }
}

Following the way PHP does it, we stick an “i” in the middle of that function name to call it endsiWith.

You can test out the function with this code which would return true …

    $haystack = "automation test";
    $needle = "test";

    if ( endsWith($haystack, $needle) ) {
        echo "$haystack end with $needle";
    } else {
        echo "$haystack does not end with $needle";
    }

And this …

    $haystack = "automation tests";
    $needle = "test";

    if ( endsWith($haystack, $needle) ) {
        echo "$haystack end with $needle";
    } else {
        echo "$haystack does not end with $needle";
    }

would return false.