SlideShare a Scribd company logo
6
Most read
7
Most read
11
Most read
Pattern Matching
Jigar Makhija
PHP Regular Expression Introduction
• Regular expressions allow you to search for and replace
patterns in strings.
PHP Regular Expression Functions
PHP preg_filter() Function
• Returns a string or an array with pattern matches
replaced, but only if matches were found
<?php
$input = [
"It is 5 o'clock",
"40 days",
"No numbers here",
"In the year 2000"
];
$result = preg_filter('/[0-9]+/', '($0)',
$input);
print_r($result);
?>
O/P:
Array
(
[0] => It is (5) o'clock
[1] => (40) days
[3] => In the year
(2000)
)
PHP Regular Expression Functions
PHP preg_grep() Function
• Returns an array consisting only of elements from the
input array which matched the pattern.
<?php
$input = [
"Red",
"Pink",
"Green",
"Blue",
"Purple"
];
$result = preg_grep("/^p/i", $input);
print_r($result);
?>
O/P:
Array
(
[1] => Pink
[4] => Purple
)
PHP Regular Expression Functions
PHP preg_last_error()
Function
• Returns an error code
indicating the reason that
the most recent regular
expression call failed.
<?php
$str = 'The regular expression is invalid.';
$pattern = '/invalid//';
$match = @preg_match($pattern, $str, $matches);
if($match === false) {
// An error occurred
$err = preg_last_error();
if($err == PREG_INTERNAL_ERROR) {
echo 'Invalid regular expression.';
}
} else if($match) {
// A match was found
echo $matches[0];
} else {
// No matches were found
echo 'No matches found';
}
?>
PHP Regular Expression Functions
PHP preg_match() Function & PHP preg_match_all()
Function
• Finds the first match of a pattern in a string
<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str);
?>
Finds all matches of a pattern in a string
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
if(preg_match_all($pattern, $str, $matches)) {
print_r($matches);
}
?>
Array
(
[0] => Array
(
[0] => ain
[1] => AIN
[2] => ain
[3] => ain
)
)
PHP Regular Expression Functions
PHP preg_replace() Function
• Returns a string where matches of a pattern (or an array
of patterns) are replaced with a substring (or an array of
substrings) in a given string
<?php
$str = 'Visit Microsoft!';
$pattern = '/microsoft/i';
echo preg_replace($pattern, 'W3Schools', $str);
?>
O/P:
Visit W3Schools!
PHP Regular Expression Functions
PHP preg_replace_callback() Function
• Given an expression and a callback, returns a string
where all matches of the expression are replaced with the
substring returned by the callback
<?php
function countLetters($matches) {
return $matches[0] . '(' . strlen($matches[0]) . ')';
}
$input = "Welcome to W3Schools.com!";
$pattern = '/[a-z0-9.]+/i';
$result = preg_replace_callback($pattern, 'countLetters',
$input);
echo $result;
?>
O/P:
Welcome(7) to(2) W3Schools.com(13)!
PHP Regular Expression Functions
PHP
preg_replace_callback_array()
Function
• Given an array associating
expressions with callbacks,
returns a string where all
matches of each expression are
replaced with the substring
returned by the callback
<?php
function countLetters($matches) {
return $matches[0] . '[' . strlen($matches[0]) . 'letter]';
}
function countDigits($matches) {
return $matches[0] . '[' . strlen($matches[0]) . 'digit]';
}
$input = "There are 365 days in a year.";
$patterns = [
'/b[a-z]+b/i' => 'countLetters',
'/b[0-9]+b/' => 'countDigits'
];
$result = preg_replace_callback_array($patterns, $inp
echo $result;
?>
O/P:
There[5letter] are[3letter] 365[3digit] days[4letter] in[2letter] a[1letter] year[4letter].
PHP Regular Expression Functions
PHP preg_split() Function
• Breaks a string into an array using matches of a regular
expression as separators
<?php
$date = "1970-01-01 00:00:00";
$pattern = "/[-s:]/";
$components = preg_split($pattern, $date);
print_r($components);
?>
Array
(
[0] => 1970
[1] => 01
[2] => 01
[3] => 00
[4] => 00
[5] => 00
)
PHP Regular Expression Functions
PHP preg_quote() Function
• Escapes characters that have a special meaning in
regular expressions by putting a backslash in front of
them
<?php
$search = preg_quote("://", "/");
$input = 'https://www.w3schools.com/';
$pattern = "/$search/";
if(preg_match($pattern, $input)) {
echo "The input is a URL.";
} else {
echo "The input is not a URL.";
}
?>
O/P:
The input is a URL.
Regular Expression Modifiers
Modifier Description
i Performs a case-insensitive search
m Performs a multiline search (patterns that search for the beginning or end of a string will
match the beginning or end of each line)
u Enables correct matching of UTF-8 encoded patterns
Regular Expression Patterns
Expression Description
[abc] Find one character from the options between the brackets
[^abc] Find any character NOT between the brackets
[0-9] Find one character from the range 0 to 9
Metacharacters
• Metacharacters are characters with a special meaning:
Metacharacter Description
| Find a match for any one of the patterns separated by | as in: cat|dog|fish
. Find just one instance of any character
^ Finds a match as the beginning of a string as in: ^Hello
$ Finds a match at the end of the string as in: World$
d Find a digit
s Find a whitespace character
b Find a match at the beginning of a word like this: bWORD, or at the end of a word like this:
WORDb
uxxxx Find the Unicode character specified by the hexadecimal number xxxx

More Related Content

What's hot (20)

PPTX
Ajax ppt - 32 slides
Smithss25
 
PPT
Exception Handling in JAVA
SURIT DATTA
 
PPTX
Statements and Conditions in PHP
Maruf Abdullah (Rion)
 
ODP
Multithreading In Java
parag
 
PPTX
Tcp/ip server sockets
rajshreemuthiah
 
PPT
Iterator Design Pattern
Varun Arora
 
PPT
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
PPTX
Multithreading in java
Raghu nath
 
PPTX
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
PPTX
Spring Boot and REST API
07.pallav
 
PPT
PHP variables
Siddique Ibrahim
 
PDF
Chap 4 PHP.pdf
HASENSEID
 
PPTX
PHP FUNCTIONS
Zeeshan Ahmed
 
PPTX
Introduction to php
Taha Malampatti
 
PPTX
Php functions
JIGAR MAKHIJA
 
PPT
Class 5 - PHP Strings
Ahmed Swilam
 
PPTX
Introduction to Angularjs
Manish Shekhawat
 
PPT
Java Collections Framework
Sony India Software Center
 
PPTX
SessionTrackServlets.pptx
Ranjeet Reddy
 
PDF
Php tutorial(w3schools)
Arjun Shanka
 
Ajax ppt - 32 slides
Smithss25
 
Exception Handling in JAVA
SURIT DATTA
 
Statements and Conditions in PHP
Maruf Abdullah (Rion)
 
Multithreading In Java
parag
 
Tcp/ip server sockets
rajshreemuthiah
 
Iterator Design Pattern
Varun Arora
 
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
Multithreading in java
Raghu nath
 
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
Spring Boot and REST API
07.pallav
 
PHP variables
Siddique Ibrahim
 
Chap 4 PHP.pdf
HASENSEID
 
PHP FUNCTIONS
Zeeshan Ahmed
 
Introduction to php
Taha Malampatti
 
Php functions
JIGAR MAKHIJA
 
Class 5 - PHP Strings
Ahmed Swilam
 
Introduction to Angularjs
Manish Shekhawat
 
Java Collections Framework
Sony India Software Center
 
SessionTrackServlets.pptx
Ranjeet Reddy
 
Php tutorial(w3schools)
Arjun Shanka
 

Similar to Php pattern matching (20)

PPT
Regular Expressions in PHP, MySQL by programmerblog.net
Programmer Blog
 
PPTX
Regular expressions in php programming language.pptx
NikhilVij6
 
PDF
Basta mastering regex power
Max Kleiner
 
PPTX
Unit 1-strings,patterns and regular expressions
sana mateen
 
PPTX
Strings,patterns and regular expressions in perl
sana mateen
 
PDF
Don't Fear the Regex - Northeast PHP 2015
Sandy Smith
 
DOCX
Regular expressionfunction
ADARSH BHATT
 
PDF
Don't Fear the Regex LSP15
Sandy Smith
 
PDF
/Regex makes me want to (weep|give up|(╯°□°)╯︵ ┻━┻)\.?/i
brettflorio
 
PDF
Don't Fear the Regex WordCamp DC 2017
Sandy Smith
 
PPTX
Regular expressions
Nicole Ryan
 
PPT
Bioinformatica 06-10-2011-p2 introduction
Prof. Wim Van Criekinge
 
PPT
Php String And Regular Expressions
mussawir20
 
PPT
Regular Expressions 2007
Geoffrey Dunn
 
ODP
Introduction To Regex in Lasso 8.5
bilcorry
 
PPTX
Bioinformatics p2-p3-perl-regexes v2013-wim_vancriekinge
Prof. Wim Van Criekinge
 
PDF
/Regex makes me want to (weep_give up_(╯°□°)╯︵ ┻━┻)/i (for 2024 CascadiaPHP)
brettflorio
 
PDF
Don't Fear the Regex - CapitalCamp/GovDays 2014
Sandy Smith
 
PPTX
Regular Expressions in PHP
Andrew Kandels
 
PPT
Form validation server side
Mudasir Syed
 
Regular Expressions in PHP, MySQL by programmerblog.net
Programmer Blog
 
Regular expressions in php programming language.pptx
NikhilVij6
 
Basta mastering regex power
Max Kleiner
 
Unit 1-strings,patterns and regular expressions
sana mateen
 
Strings,patterns and regular expressions in perl
sana mateen
 
Don't Fear the Regex - Northeast PHP 2015
Sandy Smith
 
Regular expressionfunction
ADARSH BHATT
 
Don't Fear the Regex LSP15
Sandy Smith
 
/Regex makes me want to (weep|give up|(╯°□°)╯︵ ┻━┻)\.?/i
brettflorio
 
Don't Fear the Regex WordCamp DC 2017
Sandy Smith
 
Regular expressions
Nicole Ryan
 
Bioinformatica 06-10-2011-p2 introduction
Prof. Wim Van Criekinge
 
Php String And Regular Expressions
mussawir20
 
Regular Expressions 2007
Geoffrey Dunn
 
Introduction To Regex in Lasso 8.5
bilcorry
 
Bioinformatics p2-p3-perl-regexes v2013-wim_vancriekinge
Prof. Wim Van Criekinge
 
/Regex makes me want to (weep_give up_(╯°□°)╯︵ ┻━┻)/i (for 2024 CascadiaPHP)
brettflorio
 
Don't Fear the Regex - CapitalCamp/GovDays 2014
Sandy Smith
 
Regular Expressions in PHP
Andrew Kandels
 
Form validation server side
Mudasir Syed
 
Ad

More from JIGAR MAKHIJA (20)

PPTX
Php sessions
JIGAR MAKHIJA
 
PPTX
Php server variables
JIGAR MAKHIJA
 
PDF
Db function
JIGAR MAKHIJA
 
PDF
C++ version 1
JIGAR MAKHIJA
 
PDF
C++ Version 2
JIGAR MAKHIJA
 
PPTX
SAP Ui5 content
JIGAR MAKHIJA
 
DOCX
Solution doc
JIGAR MAKHIJA
 
PDF
Overview on Application protocols in Internet of Things
JIGAR MAKHIJA
 
PDF
125 green iot
JIGAR MAKHIJA
 
PDF
Msp430 g2 with ble(Bluetooth Low Energy)
JIGAR MAKHIJA
 
PDF
Embedded system lab work
JIGAR MAKHIJA
 
PPTX
Presentation on iot- Internet of Things
JIGAR MAKHIJA
 
PPTX
Oracle
JIGAR MAKHIJA
 
PDF
Learn Japanese -Basic kanji 120
JIGAR MAKHIJA
 
PPTX
View Alignment Techniques
JIGAR MAKHIJA
 
DOCX
Letters (complaints & invitations)
JIGAR MAKHIJA
 
PDF
Letter Writing invitation-letter
JIGAR MAKHIJA
 
PPTX
Communication skills Revised PPT
JIGAR MAKHIJA
 
PPTX
It tools &amp; technology
JIGAR MAKHIJA
 
PPTX
Communication skills
JIGAR MAKHIJA
 
Php sessions
JIGAR MAKHIJA
 
Php server variables
JIGAR MAKHIJA
 
Db function
JIGAR MAKHIJA
 
C++ version 1
JIGAR MAKHIJA
 
C++ Version 2
JIGAR MAKHIJA
 
SAP Ui5 content
JIGAR MAKHIJA
 
Solution doc
JIGAR MAKHIJA
 
Overview on Application protocols in Internet of Things
JIGAR MAKHIJA
 
125 green iot
JIGAR MAKHIJA
 
Msp430 g2 with ble(Bluetooth Low Energy)
JIGAR MAKHIJA
 
Embedded system lab work
JIGAR MAKHIJA
 
Presentation on iot- Internet of Things
JIGAR MAKHIJA
 
Learn Japanese -Basic kanji 120
JIGAR MAKHIJA
 
View Alignment Techniques
JIGAR MAKHIJA
 
Letters (complaints & invitations)
JIGAR MAKHIJA
 
Letter Writing invitation-letter
JIGAR MAKHIJA
 
Communication skills Revised PPT
JIGAR MAKHIJA
 
It tools &amp; technology
JIGAR MAKHIJA
 
Communication skills
JIGAR MAKHIJA
 
Ad

Recently uploaded (20)

PPTX
Introduction to Indian Writing in English
Trushali Dodiya
 
PDF
epi editorial commitee meeting presentation
MIPLM
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PDF
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PDF
Introduction presentation of the patentbutler tool
MIPLM
 
Introduction to Indian Writing in English
Trushali Dodiya
 
epi editorial commitee meeting presentation
MIPLM
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
Introduction presentation of the patentbutler tool
MIPLM
 

Php pattern matching

  • 2. PHP Regular Expression Introduction • Regular expressions allow you to search for and replace patterns in strings.
  • 3. PHP Regular Expression Functions PHP preg_filter() Function • Returns a string or an array with pattern matches replaced, but only if matches were found <?php $input = [ "It is 5 o'clock", "40 days", "No numbers here", "In the year 2000" ]; $result = preg_filter('/[0-9]+/', '($0)', $input); print_r($result); ?> O/P: Array ( [0] => It is (5) o'clock [1] => (40) days [3] => In the year (2000) )
  • 4. PHP Regular Expression Functions PHP preg_grep() Function • Returns an array consisting only of elements from the input array which matched the pattern. <?php $input = [ "Red", "Pink", "Green", "Blue", "Purple" ]; $result = preg_grep("/^p/i", $input); print_r($result); ?> O/P: Array ( [1] => Pink [4] => Purple )
  • 5. PHP Regular Expression Functions PHP preg_last_error() Function • Returns an error code indicating the reason that the most recent regular expression call failed. <?php $str = 'The regular expression is invalid.'; $pattern = '/invalid//'; $match = @preg_match($pattern, $str, $matches); if($match === false) { // An error occurred $err = preg_last_error(); if($err == PREG_INTERNAL_ERROR) { echo 'Invalid regular expression.'; } } else if($match) { // A match was found echo $matches[0]; } else { // No matches were found echo 'No matches found'; } ?>
  • 6. PHP Regular Expression Functions PHP preg_match() Function & PHP preg_match_all() Function • Finds the first match of a pattern in a string <?php $str = "Visit W3Schools"; $pattern = "/w3schools/i"; echo preg_match($pattern, $str); ?> Finds all matches of a pattern in a string <?php $str = "The rain in SPAIN falls mainly on the plains."; $pattern = "/ain/i"; if(preg_match_all($pattern, $str, $matches)) { print_r($matches); } ?> Array ( [0] => Array ( [0] => ain [1] => AIN [2] => ain [3] => ain ) )
  • 7. PHP Regular Expression Functions PHP preg_replace() Function • Returns a string where matches of a pattern (or an array of patterns) are replaced with a substring (or an array of substrings) in a given string <?php $str = 'Visit Microsoft!'; $pattern = '/microsoft/i'; echo preg_replace($pattern, 'W3Schools', $str); ?> O/P: Visit W3Schools!
  • 8. PHP Regular Expression Functions PHP preg_replace_callback() Function • Given an expression and a callback, returns a string where all matches of the expression are replaced with the substring returned by the callback <?php function countLetters($matches) { return $matches[0] . '(' . strlen($matches[0]) . ')'; } $input = "Welcome to W3Schools.com!"; $pattern = '/[a-z0-9.]+/i'; $result = preg_replace_callback($pattern, 'countLetters', $input); echo $result; ?> O/P: Welcome(7) to(2) W3Schools.com(13)!
  • 9. PHP Regular Expression Functions PHP preg_replace_callback_array() Function • Given an array associating expressions with callbacks, returns a string where all matches of each expression are replaced with the substring returned by the callback <?php function countLetters($matches) { return $matches[0] . '[' . strlen($matches[0]) . 'letter]'; } function countDigits($matches) { return $matches[0] . '[' . strlen($matches[0]) . 'digit]'; } $input = "There are 365 days in a year."; $patterns = [ '/b[a-z]+b/i' => 'countLetters', '/b[0-9]+b/' => 'countDigits' ]; $result = preg_replace_callback_array($patterns, $inp echo $result; ?> O/P: There[5letter] are[3letter] 365[3digit] days[4letter] in[2letter] a[1letter] year[4letter].
  • 10. PHP Regular Expression Functions PHP preg_split() Function • Breaks a string into an array using matches of a regular expression as separators <?php $date = "1970-01-01 00:00:00"; $pattern = "/[-s:]/"; $components = preg_split($pattern, $date); print_r($components); ?> Array ( [0] => 1970 [1] => 01 [2] => 01 [3] => 00 [4] => 00 [5] => 00 )
  • 11. PHP Regular Expression Functions PHP preg_quote() Function • Escapes characters that have a special meaning in regular expressions by putting a backslash in front of them <?php $search = preg_quote("://", "/"); $input = 'https://www.w3schools.com/'; $pattern = "/$search/"; if(preg_match($pattern, $input)) { echo "The input is a URL."; } else { echo "The input is not a URL."; } ?> O/P: The input is a URL.
  • 12. Regular Expression Modifiers Modifier Description i Performs a case-insensitive search m Performs a multiline search (patterns that search for the beginning or end of a string will match the beginning or end of each line) u Enables correct matching of UTF-8 encoded patterns Regular Expression Patterns Expression Description [abc] Find one character from the options between the brackets [^abc] Find any character NOT between the brackets [0-9] Find one character from the range 0 to 9
  • 13. Metacharacters • Metacharacters are characters with a special meaning: Metacharacter Description | Find a match for any one of the patterns separated by | as in: cat|dog|fish . Find just one instance of any character ^ Finds a match as the beginning of a string as in: ^Hello $ Finds a match at the end of the string as in: World$ d Find a digit s Find a whitespace character b Find a match at the beginning of a word like this: bWORD, or at the end of a word like this: WORDb uxxxx Find the Unicode character specified by the hexadecimal number xxxx