Regular Expression in PHP with Examples

In this article we are going to cover Regular Expression in PHP with Examples, Advantages and uses of Regular expressions,Operations in Regular Expression, Special Character Classes in Regular Expressions.

What is Regular expression in PHP ?

Regular expression are commonly known as regex. These are nothing more than a pattern or a sequence of characters, which describe a special search pattern as text string. They are basically used in programming world algorithms for matching some loosely defined patterns to achieve some relevant tasks. Sometimes regexes are understood as a mini programming language with a pattern notation which allows the users to parse text strings.

A regular expression can be a single character, or more complicated pattern.

Regular expression can be used to perform all types of text search and text replace operations.

Advantages and uses of Regular expressions in PHP:

Regular expressions are used almost everywhere in today’s application programming.

  1. Regular expression helps the programmers to validate text string.
  2. It helps in searching specific string pattern and extracting matching results in a flexible manner.
  3. It effectively saves a lot of development time, which are in search of specific string pattern.
  4. With the help of in-built regexes functions, easy and simple solution are provided for identifying patterns.
  5. It helps in important user information validations like email address, phone numbers and IP address.
  6. Regexes are mostly used for browser detection, spam filteration , checking password strength and form validations.

Operations in Regular Expression in PHP:

OperatorDescription
^It denotes the start of string.
$It denote the end of string.
.It denotes almost any single character.
()It denotes a group of expressions.
[]It finds a range of characters e.g, [abc] means x, y or z.
[^]It finds the items which are not in range e.g, [^abc] means NOT a, b or c.
(dash)It finds for character range within the given item range e.g, [a-z] means a through z.
| (pipe)It is the logical OR e.g, x | y means x OR y.
?It denotes zero or more of preceding character or item range.
*It denotes zero or more of preceding character or item range.
+It denotes zero or more of preceding character or item range.
{n}It denotes exactly n times of preceding character or item range e.g, n{2}.
{n, }It denotes atleast n times of preceding character or item range e.g, n{2, }.
{n, m}It denotes atleast n but not more than m times e.g, n{2, 4} means 2 to 4 of n.
\It denotes the escape character.

Special Character Classes in Regular Expressions in PHP:

Special CharacterDescription
\nIt denotes a new line.
\rIt denotes a carriage return.
\tIt denote a tab.
\vIt denote a vertical tab.
\fIt denote a form feed.
\xxxIt denotes octal character xxx.
\xhhIt denote hex character hh/

Predefined functions or Regex library in PHP:  

Let us look into the quick cheat sheet of predefined functions for regular expressions in PHP.

FunctionDefination
Preg_match()This function searches for a specific pattern against some string. It return true if pattern exists and false otherwise.
Preg_match_all()This function searches for all the occurrences of string pattern against the string. This function is very useful for search and replace.
preg_replace()The preg_replace() function is similar to the preg_replace() function, except that the regular expressions can be used in search and replace.
preg_split()This function exactly works like split() function except the condition is that it accepts regular expression as an input parameter for pattern. Mainly it divides the string by a regular expression.
preg_grep()The preg_grep() function finds all the elements of input array and returns the array elements matched with regexp (relational expression) pattern.
preg_quote()Quote the regular expression characters.

Regular Expression Modifiers in PHP:

Modifiers can change how a search is performed.

ModifierDescription
iPerforms a case-insensitive search
mPerforms a multiple search
uEnables correct matching of UTF-8 encoded patterns

Regular Expression Patterns in PHP:

Bracket are used to find a range of characters:

ExpressionDescription
[abc]Find one character from the options between the brackets
[^abc]Find any character NOT between the brackets
[0-9]Find one character from the range 0 to 9

Using preg_match() function in PHP:

This function will tell you whether a string contains matches of a pattern.

Example of preg_match() function:

<!DOCTYPE html>
<html>
<body>

<?php
$pattern = '/^[a-zA-Z ]*$/';
$str = 'Welcome to FOSSTechNix';
if(preg_match($pattern, $str)) {
    echo("Name string matching with"
        . " regular expression");
}
else {
    echo("Only letters and white space"
        . " allowed in name string"); 
}
  
?>

</body>
</html>

Output:

Name string matching with regular expression
Regular Expression in PHP with Examples 1

Using preg_match_all()function in PHP:

This function will tell you how many matches were found for a pattern in a string.

Example of using preg_match_all() function:

<!DOCTYPE html>
<html>
<body>

<?php
$pattern = "/<b>(.*)<\/b>/U";
$str = "Name: <b>Shweta</b> Position: <b>Developer</b>";
preg_match_all($pattern, $str, $output);
  
echo $output[0][0]." <br> ".$output[0][1]."\n";
  
?>

</body>
</html>

Output:

Shweta
Developer
Regular Expression in PHP with Examples 2

Using preg_replace() function in PHP:

This function will replace all of the matches of the pattern in a string with another string.

Example of preg_replace() function:

<?php
 $pattern = "([0-9]+)";
 $str = "Completed diploma in 2016";
 $replacestr = "2019";
 $original = preg_replace($pattern, $replacestr, $str); 
 echo $original;   
?>

Output:

Completed diploma in 2019
Regular Expression in PHP with Examples 3

Grouping in PHP :

You can use parentheses () to apply quantifiers to entire patterns. They also can be used to select parts of the pattern to be used as a match.

Example of grouping in PHP:

<?php
$str = "Apples and bananas.";
$pattern = "/ba(na){2}/i";
$original = preg_match($pattern, $str); 
echo $original;
   
?>

Output:

1
Regular Expression in PHP with Examples 4

Conclusion:

In this article we have covered Regular Expression in PHP with Examples, Advantages and uses of Regular expressions,Operations in Regular Expression, Special Character Classes in Regular Expressions.

Related Articles:

Reference:

Regular Expression in PHP official page

Shweta Mamidwar

I am Shweta Mamidwar working as a Intern in Product Company. Likes to share knowledge.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link
Powered by Social Snap