I was wondering If I could get a regular expression which will match a string that only has alphabetic characters, and that alone.
You may use any of these 2 variants:
/^[A-Z]+$/i
/^[A-Za-z]+$/
to match an input string of ASCII alphabets.
[A-Za-z]
will match all the alphabets (both lowercase and uppercase).^
and $
will make sure that nothing but these alphabets will be matched.Code:
preg_match('/^[A-Z]+$/i', "abcAbc^Xyz", $m);
var_dump($m);
Output:
array(0) {
}
Test case is for OP's comment that he wants to match only if there are 1 or more alphabets present in the input. As you can see in the test case that matches failed because there was ^
in the input string abcAbc^Xyz
.
Note: Please note that the above answer only matches ASCII alphabets and doesn't match Unicode characters. If you want to match Unicode letters then use:
/^\p{L}+$/u
Here, \p{L}
matches any kind of letter from any language