This tutorial will discuss about a unique way to check if string ends with a letter in PHP.
Suppose we have a string and we want to make sure that string ends with any letter. It can be uppercase correct letter or a lower case letter. For this, we can use the regular expressions.
The regex pattern: ‘/[A-Za-z]$/’, matches string if it ends with a character. This can be capital character from A to Z or a lower case character from a to z. Now we can pass this regular expression in the preg_match() function along with the string. If the string ends with the letter that it will match the given regex pattern and it will return one.
We have created a separate function for this,
function endsWithLetter($str) { return preg_match('/[A-Za-z]$/', $str) === 1; }
It accepts a string is an argument and returns true if the string ends with the letter today.
Let’s see the complete example,
<?php /** * Checks if a string ends with any letter * using regular expressions (preg_match()). * * @param string $str The string to check. * @return bool True if the string ends with any letter, false otherwise. */ function endsWithLetter($str) { return preg_match('/[A-Za-z]$/', $str) === 1; } $strValue = "Last Coder"; // check if string ends with any letter if (endsWithLetter($strValue)) { echo "The string ends with a letter."; } else { echo "The string does not end with a letter."; } ?>
Output
Frequently Asked:
The string ends with a letter.
Summary
We learned about a way to check if a string ends with any letter in PHP.