PHP Check if String Contains Only Alphabets With Example

Hello Friends Today, through this tutorial, I will tell you How do you check if a string contains only alphabetic characters using PHP With Example? You can check if a string contains only alphabetic characters in PHP using regular expressions. Here’s how you can do it:

<?php
$string = "OnlyAlphabets";
if (ctype_alpha($string)) {
echo "The string contains only alphabetic characters.";
} else {
echo "The string contains non-alphabetic characters.";
}
?>

The `ctype_alpha()` function checks whether all characters in the string are alphabetic. It returns `true` if all characters are alphabetic, and `false` otherwise.

Alternatively, you can use regular expressions:

<?php
$string = "OnlyAlphabets";
if (preg_match('/^[A-Za-z]+$/', $string)) {
echo "The string contains only alphabetic characters.";
} else {
echo "The string contains non-alphabetic characters.";
}
?>

This regular expression `^[A-Za-z]+$` matches the string only if it contains one or more alphabetic characters from A to Z (both uppercase and lowercase). If the string contains any non-alphabetic character or is empty, the match fails.