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

PPTX
Php functions
PPTX
Introduction to php
PDF
JavaScript - Chapter 12 - Document Object Model
PPTX
Php cookies
PPTX
Php server variables
PPTX
PHP FUNCTIONS
PPT
Oops concepts in php
PPT
PHP - Introduction to PHP AJAX
Php functions
Introduction to php
JavaScript - Chapter 12 - Document Object Model
Php cookies
Php server variables
PHP FUNCTIONS
Oops concepts in php
PHP - Introduction to PHP AJAX

What's hot (20)

PDF
Introduction to php
PPTX
Php gd library
PDF
JavaScript - Chapter 6 - Basic Functions
PDF
Php introduction
PPT
Php with MYSQL Database
PPTX
Dom(document object model)
PPTX
Javascript
PPSX
Javascript variables and datatypes
PPTX
PHP Cookies and Sessions
PPTX
Php string function
PDF
JavaScript - Chapter 10 - Strings and Arrays
PPTX
Files in php
PDF
4.2 PHP Function
PPT
JavaScript Control Statements I
PPT
Introduction to java beans
PPT
PDF
Php array
PPTX
Introduction to PHP
PDF
JavaScript - Chapter 8 - Objects
PDF
Basics of JavaScript
Introduction to php
Php gd library
JavaScript - Chapter 6 - Basic Functions
Php introduction
Php with MYSQL Database
Dom(document object model)
Javascript
Javascript variables and datatypes
PHP Cookies and Sessions
Php string function
JavaScript - Chapter 10 - Strings and Arrays
Files in php
4.2 PHP Function
JavaScript Control Statements I
Introduction to java beans
Php array
Introduction to PHP
JavaScript - Chapter 8 - Objects
Basics of JavaScript
Ad

Similar to Php pattern matching (20)

PPTX
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
PPTX
UNIT II (7).pptx
PPTX
UNIT II (7).pptx
PPTX
Arrays syntax and it's functions in php.pptx
PPTX
Unit 2 - Regular Expression.pptx
PPTX
Unit 2 - Regular Expression .pptx
PPTX
Regular expressions in Python
PDF
Web app development_php_06
PPTX
function in php like control loop and its uses
PPTX
function in php using like three type of function
PPTX
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
PPTX
UNIT IV (4).pptx
PDF
PHP Conference Asia 2016
PPT
Class 5 - PHP Strings
PPTX
unit-4 regular expression.pptx
PPTX
Regular_Expressions.pptx
PPTX
Web Application Development using PHP Chapter 3
PDF
WordCamp Portland 2018: PHP for WordPress
PPTX
Introduction To PHP000000000000000000000000000000.pptx
PPTX
3160713_WP_GTU_Study_Material_Presentations_Unit-5_17042022102823PM.pptx
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
UNIT II (7).pptx
UNIT II (7).pptx
Arrays syntax and it's functions in php.pptx
Unit 2 - Regular Expression.pptx
Unit 2 - Regular Expression .pptx
Regular expressions in Python
Web app development_php_06
function in php like control loop and its uses
function in php using like three type of function
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
UNIT IV (4).pptx
PHP Conference Asia 2016
Class 5 - PHP Strings
unit-4 regular expression.pptx
Regular_Expressions.pptx
Web Application Development using PHP Chapter 3
WordCamp Portland 2018: PHP for WordPress
Introduction To PHP000000000000000000000000000000.pptx
3160713_WP_GTU_Study_Material_Presentations_Unit-5_17042022102823PM.pptx
Ad

More from JIGAR MAKHIJA (20)

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

Recently uploaded (20)

PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Cell Types and Its function , kingdom of life
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
master seminar digital applications in india
PDF
Basic Mud Logging Guide for educational purpose
PDF
Classroom Observation Tools for Teachers
PDF
01-Introduction-to-Information-Management.pdf
PDF
Pre independence Education in Inndia.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Complications of Minimal Access Surgery at WLH
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
Institutional Correction lecture only . . .
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
O5-L3 Freight Transport Ops (International) V1.pdf
Anesthesia in Laparoscopic Surgery in India
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Cell Types and Its function , kingdom of life
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Supply Chain Operations Speaking Notes -ICLT Program
2.FourierTransform-ShortQuestionswithAnswers.pdf
Pharma ospi slides which help in ospi learning
master seminar digital applications in india
Basic Mud Logging Guide for educational purpose
Classroom Observation Tools for Teachers
01-Introduction-to-Information-Management.pdf
Pre independence Education in Inndia.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Complications of Minimal Access Surgery at WLH
Abdominal Access Techniques with Prof. Dr. R K Mishra
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Institutional Correction lecture only . . .

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