SlideShare a Scribd company logo
1 of 10
preg_match
(PHP 4, PHP 5)
preg_match — Perform a regular expression match
Description
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int
$offset = 0 ]]] )
Searches subject for a match to the regular expression given in pattern.
Parameters
pattern
The pattern to search for, as a string.
subject
The input string.
matches
If matches is provided, then it is filled with the results of search. $matches[0] will
contain the text that matched the full pattern, $matches[1] will have the text that matched
the first captured parenthesized subpattern, and so on.
flags
flags can be the following flag:
PREG_OFFSET_CAPTURE
If this flag is passed, for every occurring match the appendant string offset will also be
returned. Note that this changes the value of matches into an array where every element
is an array consisting of the matched string at offset 0 and its string offset into subject at
offset 1.
offset
Normally, the search starts from the beginning of the subject string. The optional
parameter offset can be used to specify the alternate place from which to start the
search (in bytes).
Note:
Using offset is not equivalent to passing substr($subject, $offset) to
preg_match() in place of the subject string, because pattern can contain
assertions such as ^, $ or (?<=x). Compare:
<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>
The above example will output:
Array
(
)
while this example
<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CA
PTURE);
print_r($matches);
?>
will produce
Array
(
[0] => Array
(
[0] => def
[1] => 0
)
)
Return Values
preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an
error occurred.
preg_replace
(PHP 4, PHP 5)
preg_replace — Perform a regular expression search and replace
Description
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit
= -1 [, int &$count ]] )
Searches subject for matches to pattern and replaces them with replacement.
Parameters
pattern
The pattern to search for. It can be either a string or an array with strings.
Several PCRE modifiers are also available, including 'e' (PREG_REPLACE_EVAL),
which is specific to this function.
replacement
The string or an array with strings to replace. If this parameter is a string and the pattern
parameter is an array, all patterns will be replaced by that string. If both pattern and
replacement parameters are arrays, each pattern will be replaced by the replacement
counterpart. If there are fewer elements in the replacement array than in the pattern
array, any extra patterns will be replaced by an empty string.
replacement may contain references of the form n or (since PHP 4.0.4) $n, with the
latter form being the preferred one. Every such reference will be replaced by the text
captured by the n'th parenthesized pattern. n can be from 0 to 99, and 0 or $0 refers to
the text matched by the whole pattern. Opening parentheses are counted from left to right
(starting from 1) to obtain the number of the capturing subpattern. To use backslash in
replacement, it must be doubled ("" PHP string).
When working with a replacement pattern where a backreference is immediately
followed by another number (i.e.: placing a literal number immediately after a matched
pattern), you cannot use the familiar 1 notation for your backreference. 11, for
example, would confuse preg_replace() since it does not know whether you want the 1
backreference followed by a literal 1, or the 11 backreference followed by nothing. In
this case the solution is to use ${1}1. This creates an isolated $1 backreference, leaving
the 1 as a literal.
When using the e modifier, this function escapes some characters (namely ', ",  and
NULL) in the strings that replace the backreferences. This is done to ensure that no
syntax errors arise from backreference usage with either single or double quotes (e.g.
'strlen('$1')+strlen("$2")'). Make sure you are aware of PHP's string syntax to know
exactly how the interpreted string will look.
subject
The string or an array with strings to search and replace.
If subject is an array, then the search and replace is performed on every entry of
subject, and the return value is an array as well.
limit
The maximum possible replacements for each pattern in each subject string. Defaults to
-1 (no limit).
count
If specified, this variable will be filled with the number of replacements done.
Return Values
preg_replace() returns an array if the subject parameter is an array, or a string otherwise.
preg_quote
(PHP 4, PHP 5)
preg_quote — Quote regular expression characters
Description
string preg_quote ( string $str [, string $delimiter = NULL ] )
preg_quote() takes str and puts a backslash in front of every character that is part of the regular
expression syntax. This is useful if you have a run-time string that you need to match in some
text and the string may contain special regex characters.
The special regular expression characters are: .  + * ? [ ^ ] $ ( ) { } = ! < > | : -
Parameters
str
The input string.
delimiter
If the optional delimiter is specified, it will also be escaped. This is useful for escaping
the delimiter that is required by the PCRE functions. The / is the most commonly used
delimiter.
Return Values
Returns the quoted string.
Changelog
Version Description
5.3.0 The - character is now quoted
Examples
Example #1 preg_quote() example
<?php
$keywords = '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
echo $keywords; // returns $40 for a g3/400
?>
Example #2 Italicizing a word within some text
<?php
// In this example, preg_quote($word) is used to keep the
// asterisks from having special meaning to the regular
// expression.
$textbody = "This book is *very* difficult to find.";
$word = "*very*";
$textbody = preg_replace ("/" . preg_quote($word) . "/",
"<i>" . $word . "</i>",
$textbody);
?>
preg_split
(PHP 4, PHP 5)
preg_split — Split string by a regular expression
Description
array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )
Split the given string by a regular expression.
Parameters
pattern
The pattern to search for, as a string.
subject
The input string.
limit
If specified, then only substrings up to limit are returned with the rest of the string being
placed in the last substring. A limit of -1, 0 or NULL means "no limit" and, as is standard
across PHP, you can use NULL to skip to the flags parameter.
flags
flags can be any combination of the following flags (combined with the | bitwise
operator):
PREG_SPLIT_NO_EMPTY
If this flag is set, only non-empty pieces will be returned by preg_split().
PREG_SPLIT_DELIM_CAPTURE
If this flag is set, parenthesized expression in the delimiter pattern will be captured and
returned as well.
PREG_SPLIT_OFFSET_CAPTURE
If this flag is set, for every occurring match the appendant string offset will also be
returned. Note that this changes the return value in an array where every element is an
array consisting of the matched string at offset 0 and its string offset into subject at
offset 1.
Return Values
Returns an array containing substrings of subject split along boundaries matched by pattern.
Changelog
Version Description
4.3.0 The PREG_SPLIT_OFFSET_CAPTURE was added
4.0.5 The PREG_SPLIT_DELIM_CAPTURE was added
Examples
Example #1 preg_split() example : Get the parts of a search string
<?php
// split the phrase by any number of commas or space characters,
// which include " ", r, t, n and f
$keywords = preg_split("/[s,]+/", "hypertext language, programming");
?>
Example #2 Splitting a string into component characters
<?php
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>
Example #3 Splitting a string into matches and their offsets
<?php
$str = 'hypertext language programming';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?>
The above example will output:
Array
(
[0] => Array
(
[0] => hypertext
[1] => 0
)
[1] => Array
(
[0] => language
[1] => 10
)
[2] => Array
(
[0] => programming
[1] => 19
)
)
preg_grep
(PHP 4, PHP 5)
preg_grep — Return array entries that match the pattern
Description
array preg_grep ( string $pattern , array $input [, int $flags = 0 ] )
Returns the array consisting of the elements of the input array that match the given pattern.
Parameters
pattern
The pattern to search for, as a string.
input
The input array.
flags
If set to PREG_GREP_INVERT, this function returns the elements of the input array that do
not match the given pattern.
Return Values
Returns an array indexed using the keys from the input array.
Changelog
Version Description
4.2.0 The flags parameter was added.
4.0.4 Prior to this version, the returned array was indexed regardless of the keys of the input
Version Description
array.
If you want to reproduce this old behavior, use array_values() on the returned array to
reindex the values.
Examples
Example #1 preg_grep() example
<?php
// return all array elements
// containing floating point numbers
$fl_array = preg_grep("/^(d+)?.d+$/", $array);
?>

More Related Content

What's hot

Chapter 13.1.8
Chapter 13.1.8Chapter 13.1.8
Chapter 13.1.8
patcha535
 
11. using regular expressions with oracle database
11. using regular expressions with oracle database11. using regular expressions with oracle database
11. using regular expressions with oracle database
Amrit Kaur
 
15 practical grep command examples in linux
15 practical grep command examples in linux15 practical grep command examples in linux
15 practical grep command examples in linux
Teja Bheemanapally
 

What's hot (19)

Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Adv. python regular expression by Rj
Adv. python regular expression by RjAdv. python regular expression by Rj
Adv. python regular expression by Rj
 
Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20
 
Chapter 13.1.8
Chapter 13.1.8Chapter 13.1.8
Chapter 13.1.8
 
PHP Regular Expressions
PHP Regular ExpressionsPHP Regular Expressions
PHP Regular Expressions
 
Regular expressions and php
Regular expressions and phpRegular expressions and php
Regular expressions and php
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Basic regular expression, extended regular expression
Basic regular expression, extended regular expressionBasic regular expression, extended regular expression
Basic regular expression, extended regular expression
 
11. using regular expressions with oracle database
11. using regular expressions with oracle database11. using regular expressions with oracle database
11. using regular expressions with oracle database
 
Regular expressions in Perl
Regular expressions in PerlRegular expressions in Perl
Regular expressions in Perl
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perl
 
A regex ekon16
A regex ekon16A regex ekon16
A regex ekon16
 
8. Spread Syntax | ES6 | JavaScript
8. Spread Syntax | ES6 | JavaScript8. Spread Syntax | ES6 | JavaScript
8. Spread Syntax | ES6 | JavaScript
 
2013 - Andrei Zmievski: Clínica Regex
2013 - Andrei Zmievski: Clínica Regex2013 - Andrei Zmievski: Clínica Regex
2013 - Andrei Zmievski: Clínica Regex
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perl
 
1. Arrow Functions | JavaScript | ES6
1. Arrow Functions | JavaScript | ES61. Arrow Functions | JavaScript | ES6
1. Arrow Functions | JavaScript | ES6
 
Sed tips and_tricks
Sed tips and_tricksSed tips and_tricks
Sed tips and_tricks
 
15 practical grep command examples in linux
15 practical grep command examples in linux15 practical grep command examples in linux
15 practical grep command examples in linux
 

Similar to Regular expressionfunction

Regular expressions
Regular expressionsRegular expressions
Regular expressions
Raj Gupta
 
Unit 2 - Regular Expression.pptx
Unit 2 - Regular Expression.pptxUnit 2 - Regular Expression.pptx
Unit 2 - Regular Expression.pptx
mythili213835
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
Vince Vo
 
String variable in php
String variable in phpString variable in php
String variable in php
chantholnet
 
Manipulating strings
Manipulating stringsManipulating strings
Manipulating strings
Nicole Ryan
 

Similar to Regular expressionfunction (20)

Php, mysqlpart2
Php, mysqlpart2Php, mysqlpart2
Php, mysqlpart2
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Unit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressionsUnit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressions
 
newperl5
newperl5newperl5
newperl5
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
php_string.pdf
php_string.pdfphp_string.pdf
php_string.pdf
 
Module 3 - Regular Expressions, Dictionaries.pdf
Module 3 - Regular  Expressions,  Dictionaries.pdfModule 3 - Regular  Expressions,  Dictionaries.pdf
Module 3 - Regular Expressions, Dictionaries.pdf
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptx
 
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
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
 
PHP - Introduction to String Handling
PHP -  Introduction to  String Handling PHP -  Introduction to  String Handling
PHP - Introduction to String Handling
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
String variable in php
String variable in phpString variable in php
String variable in php
 
Manipulating strings
Manipulating stringsManipulating strings
Manipulating strings
 
Perl slid
Perl slidPerl slid
Perl slid
 
Regular_Expressions.pptx
Regular_Expressions.pptxRegular_Expressions.pptx
Regular_Expressions.pptx
 
Chapter 3: Introduction to Regular Expression
Chapter 3: Introduction to Regular ExpressionChapter 3: Introduction to Regular Expression
Chapter 3: Introduction to Regular Expression
 

Recently uploaded

Recently uploaded (20)

The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAK
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at Comcast
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 

Regular expressionfunction

  • 1. preg_match (PHP 4, PHP 5) preg_match — Perform a regular expression match Description int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] ) Searches subject for a match to the regular expression given in pattern. Parameters pattern The pattern to search for, as a string. subject The input string. matches If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on. flags flags can be the following flag: PREG_OFFSET_CAPTURE If this flag is passed, for every occurring match the appendant string offset will also be returned. Note that this changes the value of matches into an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1. offset Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search (in bytes). Note:
  • 2. Using offset is not equivalent to passing substr($subject, $offset) to preg_match() in place of the subject string, because pattern can contain assertions such as ^, $ or (?<=x). Compare: <?php $subject = "abcdef"; $pattern = '/^def/'; preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3); print_r($matches); ?> The above example will output: Array ( ) while this example <?php $subject = "abcdef"; $pattern = '/^def/'; preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CA PTURE); print_r($matches); ?> will produce Array ( [0] => Array ( [0] => def [1] => 0 ) ) Return Values preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.
  • 3. preg_replace (PHP 4, PHP 5) preg_replace — Perform a regular expression search and replace Description mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) Searches subject for matches to pattern and replaces them with replacement. Parameters pattern The pattern to search for. It can be either a string or an array with strings. Several PCRE modifiers are also available, including 'e' (PREG_REPLACE_EVAL), which is specific to this function. replacement The string or an array with strings to replace. If this parameter is a string and the pattern parameter is an array, all patterns will be replaced by that string. If both pattern and replacement parameters are arrays, each pattern will be replaced by the replacement counterpart. If there are fewer elements in the replacement array than in the pattern array, any extra patterns will be replaced by an empty string. replacement may contain references of the form n or (since PHP 4.0.4) $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and 0 or $0 refers to the text matched by the whole pattern. Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern. To use backslash in replacement, it must be doubled ("" PHP string). When working with a replacement pattern where a backreference is immediately followed by another number (i.e.: placing a literal number immediately after a matched pattern), you cannot use the familiar 1 notation for your backreference. 11, for example, would confuse preg_replace() since it does not know whether you want the 1 backreference followed by a literal 1, or the 11 backreference followed by nothing. In this case the solution is to use ${1}1. This creates an isolated $1 backreference, leaving the 1 as a literal.
  • 4. When using the e modifier, this function escapes some characters (namely ', ", and NULL) in the strings that replace the backreferences. This is done to ensure that no syntax errors arise from backreference usage with either single or double quotes (e.g. 'strlen('$1')+strlen("$2")'). Make sure you are aware of PHP's string syntax to know exactly how the interpreted string will look. subject The string or an array with strings to search and replace. If subject is an array, then the search and replace is performed on every entry of subject, and the return value is an array as well. limit The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit). count If specified, this variable will be filled with the number of replacements done. Return Values preg_replace() returns an array if the subject parameter is an array, or a string otherwise.
  • 5. preg_quote (PHP 4, PHP 5) preg_quote — Quote regular expression characters Description string preg_quote ( string $str [, string $delimiter = NULL ] ) preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters. The special regular expression characters are: . + * ? [ ^ ] $ ( ) { } = ! < > | : - Parameters str The input string. delimiter If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter. Return Values Returns the quoted string. Changelog Version Description 5.3.0 The - character is now quoted Examples Example #1 preg_quote() example <?php $keywords = '$40 for a g3/400';
  • 6. $keywords = preg_quote($keywords, '/'); echo $keywords; // returns $40 for a g3/400 ?> Example #2 Italicizing a word within some text <?php // In this example, preg_quote($word) is used to keep the // asterisks from having special meaning to the regular // expression. $textbody = "This book is *very* difficult to find."; $word = "*very*"; $textbody = preg_replace ("/" . preg_quote($word) . "/", "<i>" . $word . "</i>", $textbody); ?>
  • 7. preg_split (PHP 4, PHP 5) preg_split — Split string by a regular expression Description array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] ) Split the given string by a regular expression. Parameters pattern The pattern to search for, as a string. subject The input string. limit If specified, then only substrings up to limit are returned with the rest of the string being placed in the last substring. A limit of -1, 0 or NULL means "no limit" and, as is standard across PHP, you can use NULL to skip to the flags parameter. flags flags can be any combination of the following flags (combined with the | bitwise operator): PREG_SPLIT_NO_EMPTY If this flag is set, only non-empty pieces will be returned by preg_split(). PREG_SPLIT_DELIM_CAPTURE If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well. PREG_SPLIT_OFFSET_CAPTURE If this flag is set, for every occurring match the appendant string offset will also be returned. Note that this changes the return value in an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1. Return Values
  • 8. Returns an array containing substrings of subject split along boundaries matched by pattern. Changelog Version Description 4.3.0 The PREG_SPLIT_OFFSET_CAPTURE was added 4.0.5 The PREG_SPLIT_DELIM_CAPTURE was added Examples Example #1 preg_split() example : Get the parts of a search string <?php // split the phrase by any number of commas or space characters, // which include " ", r, t, n and f $keywords = preg_split("/[s,]+/", "hypertext language, programming"); ?> Example #2 Splitting a string into component characters <?php $str = 'string'; $chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY); print_r($chars); ?> Example #3 Splitting a string into matches and their offsets <?php $str = 'hypertext language programming'; $chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE); print_r($chars); ?> The above example will output: Array ( [0] => Array ( [0] => hypertext [1] => 0 ) [1] => Array ( [0] => language [1] => 10 ) [2] => Array
  • 9. ( [0] => programming [1] => 19 ) ) preg_grep (PHP 4, PHP 5) preg_grep — Return array entries that match the pattern Description array preg_grep ( string $pattern , array $input [, int $flags = 0 ] ) Returns the array consisting of the elements of the input array that match the given pattern. Parameters pattern The pattern to search for, as a string. input The input array. flags If set to PREG_GREP_INVERT, this function returns the elements of the input array that do not match the given pattern. Return Values Returns an array indexed using the keys from the input array. Changelog Version Description 4.2.0 The flags parameter was added. 4.0.4 Prior to this version, the returned array was indexed regardless of the keys of the input
  • 10. Version Description array. If you want to reproduce this old behavior, use array_values() on the returned array to reindex the values. Examples Example #1 preg_grep() example <?php // return all array elements // containing floating point numbers $fl_array = preg_grep("/^(d+)?.d+$/", $array); ?>