How to use Regular Expressions (Regex) In PHP
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" ); ?> |
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" ); ?> |
Invalid String
How to Check a String Contains at least One Letter and One Number in PHP ?
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.