Regular expressions in PHP

|
| By Webner

Regular expressions

Regular expressions use arithmetic operators like +,^,- and create complex expressions that can help to validate IP address, email address, telephone no, etc. They save our coding time.
Some of built-in PHP regular expressions are:

Preg_replace- perform pattern match on a string and returns true if a match is found otherwise false.

Preg_match- performs pattern match on a string and splits it into a numeric array.

Preg_split- performs pattern match on a string and replaces the match with specified text.

Syntax:

<?php
function_abc(‘/pattern/’,string);
?>

Here, “pattern” is the pattern we need to match and “string” is a text string to match.
regular expressions PHP

Some practical examples that implement the above regular expression are:

1. Preg_match
<?php
$text = "abcthisdef";
if(preg_match("/this/",$text))
{
echo "$text contains this";
}
else
{
echo "$text does not contain this";
}
?>

2. Preg_split
<?php
$my_text="Practice Regular Expressions";
$my_array = preg_split("/ /", $my_text);
print_r($my_array );
?>

o/p: Array ( [0] => Practice [1] => Regular [2] => Expressions )

Metacharacters
Metacharacters allows us to perform more complex pattern matches such as testing an email address’s validity. Some metacharacters that are commonly used:

Metacharacter
. Matches anything that has a single character except a new line /.

^ Matches the starting/beginning of the string
For eg, /^PH/ matches any string that starts with PH

$ Matches pattern at the end of the string
For eg, /com$/ matches google.com,yahoo.com etc.

* Matches any zero or more characters
For eg, /com*/ matches computer, communication, etc.

+ Requires preceding characters to appear at least one time
For eg, /yah+oo/ matches yahoo

[…] Character class
/[abc]/ matches abc

a-z Matches lower case letters
/a-z/ matches cool, happy etc.

A-Z Matches upper case letters
/A-Z/ matches WHAT, WHY etc.

0-9 Matches any number between 0 and 9
/0-4/ matches 0,1,2,3,4

Let’s take an example that checks the validity of an email address.

<?php
$email = "name@xyz.com";
if (preg_match("/^[a-zA-Z0-9.]+@[a-zA-Z0-9-]/", $email)) {
echo "$email is a valid email address";
}
else
{
echo "$email is not a valid email address";
}
?>

o/p: name@xyz.com is a valid email address

In this pattern,
“‘/…/'” is starting and ending of a regular expression
“^[a-zA-Z0-9.]” matches any lower or capital letters, numbers from 0 to 9, and dots.
“+@[a-zA-Z0-9-]” matches the @, followed by lower or capital letters and numbers from 0 to 9 or any dash.

Some more examples:

  • p?
    It matches any string which contains at least one p.
  • p{2,3}
    It matches any string containing two or three p’s.
  • p{2, }
    It matches any string containing at least two p’s.
  • p$
    It matches any string containing p at the end.
  • ^.{2}$
    It matches any string containing exactly two characters.
  • <b>(.*)</b>
    It matches any string enclosed within <b> and </b>.

PHP’s Regexp PERL Compatible Functions:

preg_match_all()
The preg_match_all() function matches all occurrences of pattern in string.

preg_grep()
The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.

preg_ quote()
Quote regular expression characters found within a string.

Some predefined Character Classes
\d – Same as [0-9], matches any digit character.
\D – It is the same as [^0-9] that matches any non-digit character.
\s – Matches any whitespace character (space, tab, or a newline).
\S – Matches non-whitespace characters.
\w – It is the same as [a-zA-Z_0-9], matches any word character (defined as a to z, A to Z,0 to 9, and the underscore).
\W – Same as [^a-zA-Z_0-9], matches any non-word character.

Examples:-

<?php
$pattern = "/\s/";
$replacement = "-";
$text = "Earth is revolving around\nthe\tSun";
// Replace spaces, newlines and tabs
echo preg_replace($pattern, $replacement, $text);
echo "<br>";
echo str_replace(" ", "-", $text);// Replace only spaces
?>

o/p: Earth-is-revolving-around-the-Sun
Earth-is-revolving-around the Sun

<?php
$pattern = "/[\s,]+/";
$text = "My favourite colors are black, yellow and blue";
$parts = preg_split($pattern, $text);
// Loop through parts array and display substrings
foreach($parts as $part){
echo $part . "<br>";
}
?>

o/p:
My
favourite
colors
are
black
yellow
and
blue

<?php
$pattern = "/^J/";
$names = array("John Carter"https://twitter.com/Webners/status/1265501342430367744, "Clark", "Johnny");
$matches = preg_grep($pattern, $names);
// Loop through matches array and display matched names
foreach($matches as $match){
echo $match . "<br>";
}
?>

o/p: John Carter
Johnny

<?php
$pattern = "/color/i";
$text = "color blue is better than color red";
$matches = preg_match_all($pattern, $text, $array);
echo $matches . " matches were found.";
?>

o/p: 2 matches were found.

<?php
$pattern = "/ca[kf]e/";
$sometext = "He is eating cake in the cafe.";
$matches = preg_match_all($pattern, $sometext, $array);
echo $matches . " matches were found.";
?>

o/p: 2 matches were found.

Leave a Reply

Your email address will not be published. Required fields are marked *