Check if String Ends With Substring in PHP

- 1 minute read

Here is a simple one-line PHP function to check whether a string ends with a given substring:

function hasEnding($str, $substr) {
    return strrpos($str, $substr) === strlen($str) - strlen($substr);
}

It could be used like this:

$sentence = 'The ball is red.';

$red = hasEnding('red.'); // TRUE

$blue = hasEnding('blue.'); // FALSE

hasEnding returns a boolean value.

It can also be used to check whether a string ends with an individual character. Here’s an example:

$path = 'C:/Files/';

$trailingSlash = hasEnding('/'); // TRUE

Link to this section Conclusion

That’s all! This is a very brief yet very handy utility function that I add to my PHP codebases all the time.

I hope you find it useful as well. Thanks for reading!