Check if String Ends with Substring in PHP

This tutorial will discuss about a unique way to check if string ends with substring in php.

Suppose we have a string, and we want to check if this string ends with a given substring. For this, we can use the substr() function in PHP. Using this function we can fetch a portion of string.

Suppose given substring is of size N, so we will fetch a substring containing last N characters from then given string. Then we can compare that to the given substring, if both are equal then it means that string ends with the given substring. We have created a function for this,

function endsWith($str, $subStr)
{
    return substr($str, -strlen($subStr)) === $subStr;
}

It accepts a string and substring as arguments, and returns true if the given string ends with give substring. Inside the function we will first calculate the size of given substring, suppose that is N. Then we will fetch last N characters from given string by passing -N as the second argument in substr() function i.e. substr($str, -strlen($subStr)). It returns a substring containing last N characters of string. Then we can match it with the given substring, if both are equal then it means that the given string ends with the given substring.

Let’s see the complete example,

<?php
/**
 * Checks if a string ends with a specific substring using substr().
 *
 * @param string $str The string to check.
 * @param string $subStr The substring to check for at the end of the string.
 * @return bool True if the string ends with the substring, false otherwise.
 */
function endsWith($str, $subStr)
{
    return substr($str, -strlen($subStr)) === $subStr;
}

$strValue = "Last Coder";
$subStr = "Coder";

if (endsWith($strValue, $subStr)) {
    echo "The string ends with the substring.";
} else {
    echo "The string does not end with the substring.";
}
?>

Output

The string ends with the substring.

Summary

We learned about a way to check if string ends with a given substring in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top