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.

Tools:

Crypto Currency

PHPKIDA provides free online the best real-time crypto market price, news, predictions, index with graphs & historical data for 2000+ coins including bitcoin, ethereum, & altcoins from major cryptocurrency exchanges.

Visite Tool

Icon Generator

PHPKIDA provides free online icon generator. Our icon generator help you to edit, modify, resize and customize icon for your website and applications. Convert to a shap you like add icon border, you can change icon border color, border size, background color, icon shadow, icons color, icon size in your own way and save it as a png image.

Visite Tool

Youtube Video Downloader

PHPKIDA provides Free online YouTube video downloader to download YouTube videos quickly in MP4, 3GP, and more. Search your video and free fast download youtube videos.

Visite Tool

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.