php-regexHow to use regex in PHP to match only letters?
Regex (Regular Expressions) is a powerful tool used to match patterns in strings. In PHP, it can be used to match only letters.
Example code
$string = 'Hello World!';
$pattern = '/[a-zA-Z]/';
if (preg_match($pattern, $string)) {
echo 'Matched!';
}
Output example
Matched!
Code explanation
$string: This is the string that we want to match against.$pattern: This is the regex pattern that we use to match against the string. In this case, it is/[a-zA-Z]/, which matches any letter from a to z, both lowercase and uppercase.preg_match(): This is the function that we use to match the string against the regex pattern. It takes two parameters, the regex pattern and the string.echo: This is the function that we use to output the result of the match.
Helpful links
More of Php Regex
- How to use PHP regex to match a zip code?
- How to match a quotation mark in PHP regex?
- How to use PHP regex to match a year?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match special characters?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match UUID?
See more codes...