Open In App

PHP Program to Check if a String Contains Uppercase, Lowercase, Special Characters and Numeric Values

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

Given a String, the task is to check whether the given string contains uppercase, lowercase, special characters, and numeric values in PHP. When working with strings in PHP, it’s often necessary to determine the presence of certain character types within the string, such as uppercase letters, lowercase letters, special characters, and numeric values.

Examples:

Input: str = "GeeksforGeeks123@#$" 
Output: Yes
Explanation: The given string contains uppercase
characters('G', 'F'), lowercase characters('e', 'k', 's', 'o', 'r'),
special characters( '#', '@'), and numeric values('1', '2', '3').
Therefore, the output is Yes.

Input: str = "GeeksforGeeks"
Output: No
Explanation: The given string contains only uppercase
characters and lowercase characters. Therefore, the
output is No.

Approach 1: Using Built-in Functions

PHP provides several built-in functions that help determine the presence of specific character types in a string.

PHP




<?php
  
function checkChars($str) {
    $upperCase = preg_match('/[A-Z]/', $str);
    $lowerCase = preg_match('/[a-z]/', $str);
    $specialChar = preg_match('/[^A-Za-z0-9]/', $str);
    $numericVal = preg_match('/[0-9]/', $str);
  
    return [
        'Uppercase' => $upperCase,
        'Lowercase' => $lowerCase,
        'Special Characters' => $specialChar,
        'Numeric Values' => $numericVal,
    ];
}
  
// Driver code
$str = "GeeksforGeeks123@#$";
$result = checkChars($str);
  
foreach ($result as $type => $hasType) {
    echo "$type: " . ($hasType ? 'Yes' : 'No') . "\n";
}
  
?>


Output

Uppercase: Yes
Lowercase: Yes
Special Characters: Yes
Numeric Values: Yes


Approach 2: Using Loop and ctype Functions

Another approach involves iterating through each character in the string and using ctype functions to check their types.

PHP




<?php
function checkChars($str) {
    $upperCase = $lowerCase = $specialChar = $numericVal = false;
  
    for ($i = 0; $i < strlen($str); $i++) {
        if (ctype_upper($str[$i])) {
            $upperCase = true;
        } else if (ctype_lower($str[$i])) {
            $lowerCase = true;
        } else if (ctype_digit($str[$i])) {
            $numericVal = true;
        } else {
            $specialChar = true;
        }
    }
  
    return [
        'Uppercase' => $upperCase,
        'Lowercase' => $lowerCase,
        'Special Characters' => $specialChar,
        'Numeric Values' => $numericVal,
    ];
}
  
// Driver code
$str = "GeeksforGeeks123@#$";
$result = checkChars($str);
  
foreach ($result as $type => $hasType) {
    echo "$type: " . ($hasType ? 'Yes' : 'No') . "\n";
}
?>


Output

Uppercase: Yes
Lowercase: Yes
Special Characters: Yes
Numeric Values: Yes




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads