SlideShare una empresa de Scribd logo
1 de 13
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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Php array
Php arrayPhp array
Php array
 
Php server variables
Php server variablesPhp server variables
Php server variables
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Php string function
Php string function Php string function
Php string function
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
 
jQuery
jQueryjQuery
jQuery
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 
Java script
Java scriptJava script
Java script
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
Document object model
Document object modelDocument object model
Document object model
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
Java script
Java scriptJava script
Java script
 
Introduction of Html/css/js
Introduction of Html/css/jsIntroduction of Html/css/js
Introduction of Html/css/js
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
 

Similar a Php pattern matching

String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering CollegeString handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering CollegeDhivyaa C.R
 
Unit 2 - Regular Expression.pptx
Unit 2 - Regular Expression.pptxUnit 2 - Regular Expression.pptx
Unit 2 - Regular Expression.pptxmythili213835
 
Unit 2 - Regular Expression .pptx
Unit 2 - Regular        Expression .pptxUnit 2 - Regular        Expression .pptx
Unit 2 - Regular Expression .pptxmythili213835
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in PythonSujith Kumar
 
Web app development_php_06
Web app development_php_06Web app development_php_06
Web app development_php_06Hassen Poreya
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Dhivyaa C.R
 
PHP Conference Asia 2016
PHP Conference Asia 2016PHP Conference Asia 2016
PHP Conference Asia 2016Britta Alex
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP StringsAhmed Swilam
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptxPadreBhoj
 
Regular_Expressions.pptx
Regular_Expressions.pptxRegular_Expressions.pptx
Regular_Expressions.pptxDurgaNayak4
 
Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3Mohd Harris Ahmad Jaal
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressAlena Holligan
 
Php basics
Php basicsPhp basics
Php basicshamfu
 
Manipulating strings
Manipulating stringsManipulating strings
Manipulating stringsNicole Ryan
 
Regular expressionfunction
Regular expressionfunctionRegular expressionfunction
Regular expressionfunctionADARSH BHATT
 

Similar a Php pattern matching (20)

UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
 
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering CollegeString handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
 
Unit 2 - Regular Expression.pptx
Unit 2 - Regular Expression.pptxUnit 2 - Regular Expression.pptx
Unit 2 - Regular Expression.pptx
 
Unit 2 - Regular Expression .pptx
Unit 2 - Regular        Expression .pptxUnit 2 - Regular        Expression .pptx
Unit 2 - Regular Expression .pptx
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Web app development_php_06
Web app development_php_06Web app development_php_06
Web app development_php_06
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
 
PHP Conference Asia 2016
PHP Conference Asia 2016PHP Conference Asia 2016
PHP Conference Asia 2016
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptx
 
Regular_Expressions.pptx
Regular_Expressions.pptxRegular_Expressions.pptx
Regular_Expressions.pptx
 
Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPress
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
php_string.pdf
php_string.pdfphp_string.pdf
php_string.pdf
 
Php basics
Php basicsPhp basics
Php basics
 
Manipulating strings
Manipulating stringsManipulating strings
Manipulating strings
 
Regular expressionfunction
Regular expressionfunctionRegular expressionfunction
Regular expressionfunction
 

Más de JIGAR MAKHIJA

Overview on Application protocols in Internet of Things
Overview on Application protocols in Internet of ThingsOverview on Application protocols in Internet of Things
Overview on Application protocols in Internet of ThingsJIGAR MAKHIJA
 
Msp430 g2 with ble(Bluetooth Low Energy)
Msp430 g2 with ble(Bluetooth Low Energy)Msp430 g2 with ble(Bluetooth Low Energy)
Msp430 g2 with ble(Bluetooth Low Energy)JIGAR MAKHIJA
 
Embedded system lab work
Embedded system lab workEmbedded system lab work
Embedded system lab workJIGAR MAKHIJA
 
Presentation on iot- Internet of Things
Presentation on iot- Internet of ThingsPresentation on iot- Internet of Things
Presentation on iot- Internet of ThingsJIGAR MAKHIJA
 
Learn Japanese -Basic kanji 120
Learn Japanese -Basic kanji 120Learn Japanese -Basic kanji 120
Learn Japanese -Basic kanji 120JIGAR MAKHIJA
 
View Alignment Techniques
View Alignment TechniquesView Alignment Techniques
View Alignment TechniquesJIGAR MAKHIJA
 
Letters (complaints & invitations)
Letters (complaints & invitations)Letters (complaints & invitations)
Letters (complaints & invitations)JIGAR MAKHIJA
 
Letter Writing invitation-letter
Letter Writing invitation-letterLetter Writing invitation-letter
Letter Writing invitation-letterJIGAR MAKHIJA
 
Communication skills Revised PPT
Communication skills Revised PPTCommunication skills Revised PPT
Communication skills Revised PPTJIGAR MAKHIJA
 
It tools &amp; technology
It tools &amp; technologyIt tools &amp; technology
It tools &amp; technologyJIGAR MAKHIJA
 
Communication skills
Communication skillsCommunication skills
Communication skillsJIGAR MAKHIJA
 

Más de JIGAR MAKHIJA (20)

Php functions
Php functionsPhp functions
Php functions
 
Php sessions
Php sessionsPhp sessions
Php sessions
 
Db function
Db functionDb function
Db function
 
C++ version 1
C++  version 1C++  version 1
C++ version 1
 
C++ Version 2
C++  Version 2C++  Version 2
C++ Version 2
 
SAP Ui5 content
SAP Ui5 contentSAP Ui5 content
SAP Ui5 content
 
Solution doc
Solution docSolution doc
Solution doc
 
Overview on Application protocols in Internet of Things
Overview on Application protocols in Internet of ThingsOverview on Application protocols in Internet of Things
Overview on Application protocols in Internet of Things
 
125 green iot
125 green iot125 green iot
125 green iot
 
Msp430 g2 with ble(Bluetooth Low Energy)
Msp430 g2 with ble(Bluetooth Low Energy)Msp430 g2 with ble(Bluetooth Low Energy)
Msp430 g2 with ble(Bluetooth Low Energy)
 
Embedded system lab work
Embedded system lab workEmbedded system lab work
Embedded system lab work
 
Presentation on iot- Internet of Things
Presentation on iot- Internet of ThingsPresentation on iot- Internet of Things
Presentation on iot- Internet of Things
 
Oracle
OracleOracle
Oracle
 
Learn Japanese -Basic kanji 120
Learn Japanese -Basic kanji 120Learn Japanese -Basic kanji 120
Learn Japanese -Basic kanji 120
 
View Alignment Techniques
View Alignment TechniquesView Alignment Techniques
View Alignment Techniques
 
Letters (complaints & invitations)
Letters (complaints & invitations)Letters (complaints & invitations)
Letters (complaints & invitations)
 
Letter Writing invitation-letter
Letter Writing invitation-letterLetter Writing invitation-letter
Letter Writing invitation-letter
 
Communication skills Revised PPT
Communication skills Revised PPTCommunication skills Revised PPT
Communication skills Revised PPT
 
It tools &amp; technology
It tools &amp; technologyIt tools &amp; technology
It tools &amp; technology
 
Communication skills
Communication skillsCommunication skills
Communication skills
 

Último

Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 

Último (20)

Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 

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