PHP | Regular Expressions - GeeksforGeeks

10 Feb, 2022
Regular expressions commonly known as a regex (regexes) are a sequence of characters describing a special search pattern in the form of text string. They are basically used in programming world algorithms for matching some loosely defined patterns to achieve some relevant tasks. Some times regexes are understood as a mini programming language with a pattern notation which allows the users to parse text strings. The exact sequence of characters are unpredictable beforehand, so the regex helps in fetching the required strings based on a pattern definition.
Regular Expression is a compact way of describing a string pattern that matches a particular amount of text. As you know, PHP is an open-source language commonly used for website creation, it provides regular expression functions as an important tool. Like PHP, many other programming languages have their own implementation of regular expressions. This is the same with other applications also, which have their own support of regexes having various syntaxes. Many available modern languages and tools apply regexes on very large files and strings. Let us look into some of the advantages and uses of regular expressions in our applications.
Advantages and uses of Regular expressions:In many scenarios, developers face problems whenever data are collected in free text fields as most of the programming deals with data entries. Regular expressions are used almost everywhere in today’s application programming.
Regular expressions help in validation of text strings which are of programmer’s interest.
It offers a powerful tool for analyzing, searching a pattern and modifying the text data.
It helps in searching specific string pattern and extracting matching results in a flexible manner.
It helps in parsing text files looking for a defined sequence of characters for further analysis or data manipulation.
With the help of in-built regexes functions, easy and simple solutions are provided for identifying patterns.
It effectively saves a lot of development time, which are in search of specific string pattern.
It helps in important user information validations like email address, phone numbers and IP address.
It helps in highlighting special keywords in a file based on search result or input.
It helps in identifying specific template tags and replacing those data with the actual data as per the requirement.
Regexes are very useful for creation of HTML template system recognizing tags.
Regexes are mostly used for browser detection, spam filtration, checking password strength and form validations.
We cannot cover everything under this topic, but let us look into some of the major regular expression concepts. The following table shows some regular expressions and the corresponding string which matches the regular expression pattern.
Note: Complex search patterns can be created by applying some basic regular expression rules. Even many arithmetic operators like +, ^, – are used by regular expressions for creating little complex patterns.
Operators in Regular Expression: Let us look into some of the operators in PHP regular expressions.
Special Character Classes in Regular Expressions: Let us look into some of the special characters used in regular expressions.
Shorthand Character Sets: Let us look into some shorthand character sets available.
Predefined functions or Regex library: Let us look into the quick cheat sheet of pre-defined functions for regular expressions in PHP. PHP provides the programmers to many useful functions to work with regular expressions.
The below listed in-built functions are case-sensitive.
Note:
By default, regular expressions are case sensitive.
There is a difference between strings inside single quotes and strings inside double quotes in PHP. The former are treated literally, whereas for the strings inside double-quotes means the content of the variable is printed instead of just printing their names.
Example 1:
<?php // Declare a regular expression$regex = '/^[a-zA-Z ]*$/'; // Declare a string$nameString = 'Sharukh khan'; // Use preg_match() function to// search string patternif(preg_match($regex, $nameString)) {    echo("Name string matching with"        . " regular expression");}else {    echo("Only letters and white space"        . " allowed in name string");} ?>
Output:
Name string matching with regular expression
Example 2:
<?php // Declare a regular expression$regex = "/<b>(.*)<\/b>/U"; // Declare a string$inputString = "Name: <b>John</b> Position: <b>Developer</b>"; // Use preg_match_all() function to perform// a global regular expression matchpreg_match_all($regex, $inputString, $output); echo $output[0][0]." <br> ".$output[0][1]."\n"; ?>
Output:
John
Developer

Example 3:
<?php // Declare a regular expression$regex = "([0-9]+)"; // Declare a string$original = "Completed graduation in 2004";$replaceWith = "2002";  // Use ereg_replace() function to search a// string pattern in an other string$original = ereg_replace($regex, $replaceWith, $original);     // Display resultecho $original;  ?>
Output:
Completed graduation in 2002
Example 4:
<?php<?php // Declare a string$ip = "134.645.478.670"; // Declare a regular expression$regex = "/\./"; // Use preg_split() function to// convert a given string into// an array$output = preg_split ($regex, $ip); echo "$output[0] <br>";echo "$output[1] <br>";echo "$output[2] <br>";echo "$output[3] <br>"; ?>
Output:
134
645
478
670

Metacharacters: There are two kinds of characters that are used in regular expressions these are: Regular characters and Metacharacters. Regular characters are those characters which have a ‘literal’ meaning and Metacharacters are those characters which have ‘special’ meaning in regular expression.
Other Examples:
Note:
Metacharacters are very powerful in regular expressions pattern matching solutions. It handles a lot of complex pattern processing.
Every character which is not a metacharacter is definitely a regular character.
Every regular character matches the same character by itself.
POSIX Regular Expressions: Some regular expressions in PHP are like arithmetic expressions which are called POSIX regular expressions. Some times, complex expression are created by combining various elements or operators in regular expressions. The very basic regex is the one which matches a single character.
Lets look into some of the POSIX regular expressions.
Quantifiers in Regular Expression: Quantifiers are special characters which tell the quantity, frequency or the number of instances or occurrence of bracketed character or group of characters. They are also called as greedy and lazy expressions. Let us look into some of the concepts and examples of quantifiers.
Note:
The $ character inside the expression will match the end of the target string.
The *, ?, + symbols in a regular expression denotes the frequency of occurrence of a character. If it occurs zero or more time, zero or one time and one or more times.
The ^ character inside the expression will match the beginning of the target string.
The . metacharacter matches any single character other than the newline.
Commonly known regular expression engines:
Regexp
RegexBuddy
Conclusion: A regular expression is a pattern that describes some string text in a particular pattern or it is defined as a pattern-matching algorithm expressed in a single line. Regular expressions are very useful in the programming world for validation checks and recognizing specific templates. PHP provides many in-built functions supporting regular expressions. Metacharacters helps in creating complex patterns.
nidhi_biet
clintra
gabaa406
adnanirshad158
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to execute PHP code using command line ?
How to pop an alert message box using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?