PHP Regular Expression

Regular expressions are a powerful tool for sequence or pattern of characters itself. Regular expressions themselves, with a general pattern notation almost like a mini programming language, allow you to describe and parse text. They enable you to search for patterns within a string, extracting matches flexibly and precisely, mostly use for validations and url redirection. However, you should note that because regular expressions are more powerful, they are also slower than the more basic string functions. You should only use regular expressions when you have need.

Why to use regular expressions

  • Regular expressions simplify identifying patterns in string data by calling a single function. This is saves us coding time.
  • When validating user input such as name, email address, domain names, phone numbers, IP addresses etc.
  • Highlighting keywords in search results<./li>
  • When creating a custom HTML template. Regular expressions can be used to identify the template tags and replace them with actual data.

Regular expressions in PHP

PHP has some built in functions that allow us to work with regular functions. Let’s see most commonly used regular expression functions in PHP.

preg_match – This function is used for pattern match on a string. It returns true if a match is found and false if a match is not found.
preg_split – This function is used for pattern match on a string and then split the results into a numeric array.
preg_replace – This function is used for pattern match on a string and then replace the match with the specified text.

PHP Preg_match

In below code we showing you syntax for a regular expression function preg_match.

<?php
$my_url = "www.phpkida.com";
if (preg_match("/php/", $my_url))
{
echo "the url $my_url contains php text.";
}
else
{
echo "the url $my_url does not contain php text.";
}
?>

PHP Preg_split

In below example i am showing how to use preg_split function.

<?php

$my_text="I Like Regular Expressions";
$my_array  = preg_split("/ /", $my_text);
print_r($my_array );
?>

PHP Preg_replace

In below example i am showing how to use Preg_replace function.

<?php

$text = "You are reading at phpkida.com, this is only for testing.";

$text = preg_replace("/php/", '<span style="background:yellow">Guru</span>', $text);

echo $text;

?>

Meta characters for validations

The below table showing some meta characters simply allow us to perform more complex pattern matches which are mostly used for form validations such as name, email, phone number, ip address, urls etc.

MetacharacterDescriptionExample
.Matches any single character except a new line/./ matches anything that has a single character
^Matches the beginning of or string / excludes characters/^PH/ matches any string that starts with PH
$Matches pattern at the end of the string/com$/ matches guru99.com,yahoo.com Etc.
*Matches any zero (0) or more characters/com*/ matches computer, communication etc.
+Requires preceding character(s) appear at least once/yah+oo/ matches yahoo
\Used to escape meta characters/yahoo+\.com/ treats the dot as a literal value
[…]Character class/[abc]/ matches abc
a-zMatches lower case letters/a-z/ matches cool, happy etc.
A-ZMatches upper case letters/A-Z/ matches WHAT, HOW, WHY etc.
0-9Matches any number between 0 and 9/0-4/ matches 0,1,2,3,4

How to match only numbers

This is use for matching any number between 0 and 9. let’s see below example.

<?php
$my_no = "12345"
if (preg_match("/^[0-9]$/", $my_no)) {
echo "$my_no is a valid numbers.";
}
else
{
  echo "$my_no is NOT a valid numbers";
}
?>

Email address validation pattern

Here i am explaining complex example of checking email address validation.

<?php
$my_email = "myemail@example.com"
if (preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+.[a-zA-Z.]{2,5}$/", $my_email)) {
echo "$my_email is a valid email address";
}
else
{
  echo "$my_email is NOT a valid email address";
}
?>

Below explaining the pattern “[/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/]”

  • “‘/…/'” This is use for the starts and ends the regular expression.
  • “^[a-zA-Z0-9._-]” This is use for matches any lower or upper case letters, numbers between 0 to 9 and dots, underscores or dashes.
  • “+@[a-zA-Z0-9-]” This is use for matches the @ symbol followed by lower or upper case letters, numbers between 0 to 9 or dashes.
  • “+\.[a-zA-Z.]{2,5}$/” This is use for escapes the dot using the backslash then matches any lower or upper case letters with a character length between 2 and 5 at the end of the string.

PHPKIDA Offering Free Tools:

INSTA DOWNLOADER

Free online tool to download Instagram videos, photos and save Instagram videos, photos to your device. It's free & easy to use.

Download Now

CURRENCY CONVERTER

Our real time currency converter calculator will convert your money based on current values from around the world. It's free & easy to use.

Convert Now

ROBOST.TXT GEN.

Create robots txt file that help search engines to crawling and indexing your site with help of our free online Robots.txt Generator tool.

Create Now

HTML MINIFIER

Free online tool to minify or compress html code and reduce the size of html code in few clicks. It's free & easy to use.

Minify Now

CSS MINIFIER

Free online tool to minify or compress css code and reduce the size of css code in few clicks. It's free & easy to use.

Minify Now

JAVASCRIPT MINIFIER

Free online tool to minify or compress javascript code and reduce the size of javascript code in few clicks. It's free & easy to use.

Minify Now

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.