Check if String Ends With a Specific Character in PHP

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

Suppose we have a string and a specific character i.e.

$strValue = "Last Coder!";
$character = "!";

Now we want to check if the string $strValue ends with this specific character $character or not.

For this we are going to use this substr() function to fetch the last character of the string. The substr() function accept a string and offset values in an argument, and returns a substring from that offset position till the end of the string.

To find the last character of the string we will pass the string and offset -1 as arguments in the substr() function. It will return the last character of the string. Then we will match this character with the given character to make sure that the string ends with a specific character. But before that we need to make sure that string has more than zero characters.

We have created a separate function for this,

function endsWithCharacter($str, $character)
{
    return  strlen($str) > 0 &&
            substr($str, -1) === $character;
}

It accepts a string and character as an argument and returns true if the string ends with the given character.

Let’s see the complete example,

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

$strValue = "Last Coder!";
$character = "!";

// Check if string ends with the caharcter '!'
if (endsWithCharacter($strValue, $character)) {
    echo "The string ends with the character.";
} else {
    echo "The string does not end with the character.";
}
?>

Output

The string ends with the character.

Summary

We learned about a way to check if string ends with a given character 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