This tutorial will discuss about unique ways to check if string starts with a letter in php.
Table Of Contents
Method 1: Using Regex
PHP provides a function preg_match()
, it accepts a regex pattern as first parameter and a string as the second parameter. If the string matches the given regex pattern, then it returns 1 otherwise it returns 0.
So to check if a string starts with the letter or not we will use this regex pattern i.e. “/^[a-zA-Z]/”.
We have created a separate function to check if string starts with a letter,
function startsWithLetter($str) { return preg_match('/^[a-zA-Z]/', $str) === 1; }
This function returns true if This string starts with any letter.
Let’s see the complete example,
Frequently Asked:
- Check if String Contains only Numbers in PHP
- Check if String contains a Date in PHP
- Check if String Contains SubString (Case Insensitive) in PHP
- Check if String Contains a Character in PHP
<?php /** * Checks if a string starts with a letter using * regular expressions (preg_match()). * * @param string $str The string to check. * @return bool True if the string starts with a letter, false otherwise. */ function startsWithLetter($str) { return preg_match('/^[a-zA-Z]/', $str) === 1; } $strValue = "Last Train"; // Check if String starts with a Alphabet or Letter if (startsWithLetter($strValue)) { echo "The string starts with a letter."; } else { echo "The string does not start with a letter."; } ?>
Output
The string starts with a letter.
Method 2: Using ctype_alpha() function
PHP provides a function ctype_alpha()
, which accepts a string as an argument and returns true if all the characters in the string are alphabetic only i.e. letters only.
So, to check if string starts with the a letter, we will fetch the first character from the string and we will pass into the ctype_alpha()
function, if it returns true then it means that the string starts with the alphabet or a letter.
Let’s see the complete example,
<?php /** * Checks if a string starts with a letter using ctype_alpha(). * * @param string $str The string to check. * @return bool True if the string starts with a letter, false otherwise. */ function startsWithAlphabet($str) { return ctype_alpha($str[0]); } $strValue = "Last Train"; // Check if String starts with a Alphabet or Letter if (startsWithAlphabet($strValue)) { echo "The string starts with a letter."; } else { echo "The string does not start with a letter."; } ?>
Output
The string starts with a letter.
Summary
Today, we learned about two different ways to check if string starts with the letter in PHP.