CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • 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
Home Programming Beginners Guide To Use Regular Expression In PHP

Beginners Guide To Use Regular Expression In PHP

Rana Ahsan January 9, 2011 Leave a Comment


 Beginners Guide To Use Regular Expression In PHP    

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 🙂

Related

Filed Under: Programming Tagged With: php, regular expression

About Rana Ahsan

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

Leave a Reply Cancel reply

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

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
  • Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
  • LinQ To SQL Database Update Operations In C#
  • Utilizing Config File In C#.NET Application
  • Tutorial On Uploading File With CodeIgniter Framework / PHP
  • Using GIT Plugin For Netbeans IDE

Recent Tutorials

  • 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
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • S. Chalisque on PHP HTML5 Video Streaming Tutorial
  • Armorik on Generate HTTP Requests using c#
  • iswaps on PHP HTML5 Video Streaming Tutorial
  • TAKONDWA on PHP HTML5 Video Streaming Tutorial
  • rorenzo on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2022 · CodeSamplez.com ·

Copyright © 2022 · Streamline Pro Theme on Genesis Framework · WordPress · Log in