Open In App

How to Check a String Contains at least One Letter and One Number in PHP ?

Last Updated : 17 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

This article will show you how to check if a string has at least one letter and one number in PHP. Validating whether a string contains at least one letter and one number is a common requirement. In this article, we will explore various approaches to achieve this task in PHP.

Using Regular Expressions (Regex)

Regular expressions are a powerful tool for pattern matching in strings. We can use a regular expression to check if a string contains at least one letter and one number.

The hasLetterAndNumber() function uses two regular expressions, one for checking if there is at least one letter (/[a-zA-Z]/) and the other for checking if there is at least one number (/[0-9]/). The && operator ensures both conditions are met.

Example 1:

PHP




<?php
  
function hasLetterAndNumber($str) {
    return preg_match('/[a-zA-Z]/', $str
        && preg_match('/[0-9]/', $str);
}
  
// Driver code
$str = "abc123";
  
echo (hasLetterAndNumber($str) ? 
    "Valid String" : "Invalid String");
  
?>


Output

Valid String

Example 2:

PHP




<?php
  
function hasLetterAndNumber($str) {
    return preg_match('/[a-zA-Z]/', $str
        && preg_match('/[0-9]/', $str);
}
  
// Driver code
$str = "Geeks@#$";
  
echo (hasLetterAndNumber($str) ? 
    "Valid String" : "Invalid String");
  
?>


Output

Invalid String


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads