• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Programming / Beginners Guide To Use Regular Expression In PHP

Beginners Guide To Use Regular Expression In PHP

January 9, 2011 by Rana Ahsan Leave a Comment

PHP Regular Expression Tutorials

Regular expression is so useful that most of the popular programming language includes engine to support this amazing pattern matching concept. Today, I will try to describe basic regular expression implementation concept in php programming language. If you are comparatively very new at regular expression programming, you might Want to read about regular expression basics first , what i have discussed earlier on this blog, intended for complete beginners.

Basic PHP Regular Expression Functions:

PHP have several core handy functions to utilize regular expression. All of them are with ‘preg_’ prefix in the method name. If you are using an ID that supports intelligence on PHP functionality(Like Netbeans, PHPStorms etc), you can see the whole list of those functions by typing this prefix. Here are some most commonly used functions along with some code samples on how to use those functions:

Regular expressions in PHP

preg_grep : This method matches a set of strings against a given pattern. This takes 2 parameters , one is the pattern against which to be matched and an array list of strings, which are to be matched. This method returns an array which consists a filtered list of the matched array strings those matched successfully against the pattern.

$matches = preg_grep("/{pattern}/i",$input_array);
print_r($matches);

preg_match : This method finds occurrence of one or more pattern matched sub-string inside another string. This method also takes 2 parameters , one is the pattern against which to be matched and a string value, which is to be matched. It returns either 0 or 1, depending on whether any match found or not. It’s good for getting a generic true/false result whether a match found or not.

if (preg_match("/test/i", "A very simple test message for php regex tutorial example.")) {
    echo "Input string matched with the pattern";
} else {
    echo "Input string didn't match with the pattern";
}

This function also takes an optional third array parameter as reference, all matched string/substring are returned on that referenced variable.

$matches = array();
preg_match("/test/i", "simple test with two test substring", $matches);
echo "matched strings are: \n";
print_r($matches);

preg_match_all : This is same as the previous method. Only difference is, it returns exact number of times a match found.Also it takes an extra parameter and reference variable where all matches are stored(this parameter was optional in case of preg_match).

$input = {input string to be matched};
echo "matches found ".preg_match_all("/{pattern}/", $input, $matches)." times";
//use can use $matches as an array list of matched string

preg_quote : This method is used to escape regular expression specific special characters(the characters those are used as delimiter in regex pattern). It takes the input string that is to be escaped and returns the resultant string.

$input_string = 'price of a item is $30';
$input_string = preg_quote($keywords);
echo $input_string; //put an '\' character in front of the '$' sign as that is used as an regular expression syntax

preg_replace : This method is used to replace a specific type of sub-strings that matches a pattern inside long string texts. This takes 3 parameters one is the pattern, one is the replace terms to be used and last one is the long string that is to be searched for.

$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = 'Month: ${1} <br/> Date:${2} <br/> Year:${3}';
echo preg_replace($pattern, $replacement, $string);

preg_split : This method is used to split up a long strings in some places where specific patterns are found. This takes 2 parameters, one is the pattern and other is the input string. I returns an array of strings containing the spitted strings.

$str = '{a long string to split}';
$chars = preg_split('/{pattern}/', $str);
print_r($chars);

Further References:

Hopefully this regular expression tutorial in php code examples will help you only to develop the basic concept. Besides, PHP has a very good well documentation for its core functionality references. Same applies for regular expression functions also. You can the function list on php.net regular expression functions list page. There you will also find individual links for each functions. Each of them has basic documentation with function signatures along with community provided examples. Hope they will help you better understanding. If you are facing any issue, please let me know. Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Programming Tagged With: php, regular expression

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Leave a Reply Cancel reply

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

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Beginning Codeigniter Application Development
    Beginning Codeigniter Application Development
  • Beginning With Facebook Graph API C#.NET
    Beginning With Facebook Graph API C#.NET
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • "Facebooksdk" - C#.NET Library For Facebook API
    "Facebooksdk" - C#.NET Library For Facebook API

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Popular Tutorials

  • PHP HTML5 Video Streaming Tutorial
  • How To Work With JSON In Node.js / JavaScript
  • Using Supervisord Web Interface And Plugin
  • How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
  • Get Facebook C# Api Access Token
  • Beginning Codeigniter Application Development
  • Beginning With Facebook Graph API C#.NET
  • LinQ Query With Like Operator
  • "Facebooksdk" - C#.NET Library For Facebook API

Recent Tutorials

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023