Check if String Contains Letters in PHP

This tutorial will discuss how to check if string contains letters in PHP.

To check if a string contains any Letter in PHP, we can utilize regular expressions.

The regex pattern that we can use is as follows,

'/[a-zA-Z]/'

By passing this regex pattern and the string to the preg_match() function, we can determine if the given string contains any Letter. If preg_match() returns 1, it means that the string contains any Letter.

We have created a separate function,

function containsLetters($strValue)
{
    return preg_match('/[a-zA-Z]/', $strValue) === 1;
}

It accepts a string as an argument and returns true if the string contains any Letter in it. The function internally uses the preg_match() function with the provided regex pattern to perform the check.

Let’s see the complete example,

<?php
/**
 * Check if a string contains few letters at least.
 *
 * @param string $strValue The string to validate.
 * @return bool True if the string contains letters, false otherwise.
 */
function containsLetters($strValue)
{
    return preg_match('/[a-zA-Z]/', $strValue) === 1;
}

$strValue = '220 Baker Street';

// Check if string contains some letters
if (containsLetters($strValue)) {
    echo "The string contains letters.";
} else {
    echo "The string does not contain letters.";
}
?>

Output

The string contains letters.

Summary

Today, we learned how to check if string contains letters in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top