OneBite.Dev - Coding blog in a bite size

Check If A String Contains Only Letters In PHP

Code snippet for how to Check If A String Contains Only Letters In PHP with sample and detail explanation

Checking if a string in PHP contains only letters is a common requirement in web development. This can be easily achieved by using certain built-in functions in PHP. In this article, we will explore how you can verify if a given string consists of only letters using a few lines of PHP code.

Code snippet: Checking If A String Contains Only Letters In PHP

The following is a PHP code snippet that checks if a given string contains only letters:

function is_string_alphabet_only($str){
  return preg_match("/^[A-Za-z]+$/", $str);
}

$testStr = 'OnlyLettersHere';
echo (is_string_alphabet_only($testStr) ? 'String contains only letters' : 'String contains other characters');

Code Explanation: Checking If A String Contains Only Letters In PHP

The function is_string_alphabet_only($str) checks whether the given string $str consists of only alphabetic characters.

In the body of the function, the PHP preg_match() function is used. This function performs a regular expression match.

The regular expression "/^[A-Za-z]+$/" checks for one or more occurrences of any letter (uppercase or lowercase) from the beginning to the end of the string. If the string contains any character other than a letter, the function will return false.

The ^ character means “start of line”, the $ character means “end of line”, [A-Za-z] means any letter between A and Z or between a and z, and + means “one or more occurrences”.

The function will return 1 (true) if the string contains only letters, and 0 (false) otherwise.

The test code $testStr = 'OnlyLettersHere'; echo (is_string_alphabet_only($testStr) ? 'String contains only letters' : 'String contains other characters'); will print ‘String contains only letters’ if the $testStr contains only letters and ‘String contains other characters’ if it contains any character other than letters.

Hence, with just a few lines of code, we can check if a string is made up of only letters in PHP.

php