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 nbsp HTML whitespace?
- How to match a double quote in PHP regex?
- How to use PHP regex to match URL path?
- How to get last matched occurrence in PHP regex?
- How to use PHP regex with zero or more occurrences?
- How to convert a PHP regex to JavaScript regex?
- How to use PHP regex to match an exact string?
- How to use PHP regex with the "x" modifier?
- How to match a space using PHP regex?
- How to use an "or" condition in PHP regex?
See more codes...