Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
PHP Program To Check If A String Is Substring Of Another
Next article icon

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

Last Updated : 05 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
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.

here are some common approaches:

Table of Content

  • Using Built-in Functions
  • Using Loop and ctype Functions
  • Using filter_var and Custom Validation

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

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

Using filter_var and Custom Validation

This approach uses filter_var in combination with custom validation logic to check for the presence of uppercase, lowercase, special characters, and numeric values.

PHP
<?php // Nikunj Sonigara function checkChars($str) {     $upperCase = $lowerCase = $specialChar = $numericVal = false;      $upperCase = filter_var($str, FILTER_VALIDATE_REGEXP,                              array("options"=>array("regexp"=>"/[A-Z]/"))) !== false;     $lowerCase = filter_var($str, FILTER_VALIDATE_REGEXP,                              array("options"=>array("regexp"=>"/[a-z]/"))) !== false;     $specialChar = filter_var($str, FILTER_VALIDATE_REGEXP,                                array("options"=>array("regexp"=>"/[^A-Za-z0-9]/"))                              ) !== false;     $numericVal = filter_var($str, FILTER_VALIDATE_REGEXP,                               array("options"=>array("regexp"=>"/[0-9]/"))) !== false;      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 

Next Article
PHP Program To Check If A String Is Substring Of Another

V

vkash8574
Improve
Article Tags :
  • Web Technologies
  • PHP
  • PHP Programs
  • Geeks Premier League
  • PHP-string
  • Geeks Premier League 2023

Similar Reads

  • PHP to Check if a String Contains any Special Character
    Given a String, the task is to check whether a string contains any special characters in PHP. Special characters are characters that are not letters or numbers, such as punctuation marks, symbols, and whitespace characters. Examples: Input: str = "Hello@Geeks"Output: String contain special character
    3 min read
  • 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. Table of Content Using
    3 min read
  • PHP Program To Check If A String Is Substring Of Another
    Given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1. Examples: Input: s1 = "for", s2 = "geeksforgeeks"Output: 5Explanation: String "for" is present as a substring of s2.Input: s1 = "practice", s2 = "geeksforgeeks"Output: -1.E
    2 min read
  • PHP Program to Check if Two Strings are Same or Not
    Given two strings, the task is to check whether two strings are same or not in PHP. In this article, we will be looking at different approaches to check two strings are same or not. Examples: Input: str1 = "Geeks", str2 = "Geeks" Output: Both Strings are the same Input: str1 = "Hello", str2 = "Geeks
    2 min read
  • How to check if URL contain certain string using PHP?
    Given a URL and the task is to check the URL contains certain string or not. The URL are basically the strings. So in order to check the existence of certain strings, two approaches can be followed. The first approach is used to find the sub string matching in a string and second approach is to find
    4 min read
  • PHP Program to Find Missing Characters to Make a String Pangram
    In this article, we will see how to find the missing characters to make the string Pangram using PHP. A pangram is a sentence containing every letter in the English Alphabet. Examples: Input: The quick brown fox jumps over the dogOutput: Missing Characters - alyzInput: The quick brown fox jumpsOutpu
    2 min read
  • How to determine if an array contains a specific value in PHP?
    Determining if an array contains a specific value in PHP involves verifying whether a particular element exists within an array. This task is essential for various programming scenarios, such as searching for user input, validating data, or filtering results based on specific criteria. PHP offers se
    2 min read
  • How to remove all non-printable characters in a string in PHP?
    Given a string which contains printable and not-printable characters. The task is to remove all non-printable characters from the string. Space ( ) is first printable char and tilde (~) is last printable ASCII characters. So the task is to replace all characters which do fall in that range means to
    2 min read
  • PHP Program to Convert String to ASCII Value
    Given a String the task is to convert the given string into ASCII code using PHP. ASCII is the American Standard Code for Information Interchange, which is a widely used standard for encoding characters in computers and digital communication systems. There are two methods to convert a given String i
    2 min read
  • PHP Program to Count Number of Vowels in a String
    Given a String, the task is to count the number of Vowels in a given string in PHP. Counting the number of vowels in a string is a common programming task, often encountered in text processing and data analysis. Here, we will cover three common scenarios for counting the number of Vowels in a String
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences