


How to use regular expressions for find and replace in PHP_PHP Tutorial
1. preg_match — Perform a regular expression match
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
Search for a match between subject and the regular expression given by pattern.
pattern:
Pattern to be searched, string type.
subject:
Input string.
matches:
If the parameter matches is provided, it will be populated as search results. $matches[0] will contain the text matched by the full pattern, $matches[1] will contain the text matched by the first captured subgroup, and so on.
flags:
flags can be set to the following flag values: PREG_OFFSET_CAPTURE If this flag is passed, the string offset (relative to the target string) will be returned for each occurrence of a match. Note: This will change the array filled in the matches parameter so that each element becomes a string where the 0th element is the matched string and the 1st element is the offset of the matched string in the target string subject. .
offset:
Normally, the search starts from the beginning of the target string. The optional parameter offset is used to specify the search starting from an unknown point in the target string (unit is bytes).
Return value:
preg_match() returns the number of matches for pattern. Its value will be 0 (no match) or 1 because preg_match() will stop searching after the first match. preg_match_all() is different from this, it will search the subject until it reaches the end. If an error occurs preg_match() returns FALSE.
Example:
/*
* The "i" mark after the pattern separator is a case-insensitive search
* will output: 1
*/
echo preg_match("/,s*(php)/i", "In my point, PHP is the web scripting language of choice.");
echo "
"."n";
/*
*will output:Array([ 0]=>, PHP [1]=>PHP)
*/
$matches = array();
preg_match("/,s*(php)/i", "In my point, PHP is the web scripting language of choice. I love php", $matches);
print_r($matches);
echo "
"."n";
/ *
*Will output:Array([0]=>Array([0]=>, PHP [1]=>11) [1]=>Array([0]=>PHP [1]=>13))
*/
preg_match("/,s*(php)/i", "In my point, PHP is the web scripting language of choice. I love php", $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
echo "
"."n";
/*
*will output:Array([0] =>Array([0]=>e php [1]=63) [1]=>Array([0]=>php [1]=>65))
*/
preg_match("/[,a-z]?s*(php)/i", "In my point, PHP is the web scripting language of choice. I love php", $matches, PREG_OFFSET_CAPTURE, 28);
print_r ($matches);
echo "
"."n";
?>
2.preg_match_all — execute a global Regular expression matching
int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )
Search all matching results in the subject that match the given regular expression pattern and output them to matches in the order specified by flag. After the first match is found, the subsequence continues to search from the last matching position.
pattern:
The pattern to search for, in string form.
subject:
Input string.
matches:
Multi-dimensional array, output all matching results as output parameters, array sorting is specified by flags.
flags:
can be used in combination with the following tags (note that PREG_PATTERN_ORDER and PREG_SET_ORDER cannot be used at the same time). If no sorting tag is given, it is assumed to be set to PREG_PATTERN_ORDER:
PREG_PATTERN_ORDER:
The result is sorted as $matches[0 ] saves all matches of the complete pattern, $matches[1] saves all matches of the first subgroup, and so on.
PREG_SET_ORDER:
The results are sorted as $matches[0] contains all matches (including subgroups) from the first match, $matches[1] contains all matches (including subgroups) from the second match ), and so on.
PREG_OFFSET_CAPTURE:
If this flag is passed, each found match is returned with its offset relative to the target string increased. Note that this will change each match result string element in matches so that it becomes a match result string whose 0th element is the match result string and the first element is the offset of the match result string in the subject.
Return Value:
Returns the number of complete matches (possibly 0), or FALSE if an error occurs.
Example:
/*
*将会输出:2
*/
echo preg_match_all("/php/i", "In my point, PHP is the web scripting language of choice. I love php", $matches);
echo "
"."n";
/*
*将会输出:Array([0]=>, PHP [1]=>PHP)
*/
$matches = array();
preg_match("/[,a-z]?s*(php)/i", "In my point, PHP is the web scripting language of choice. I love php", $matches);
print_r($matches);
echo "
"."n";
/*
*将会输出:Array([0]=>Array([0]=>, PHP [1]=>e php) [1]=>Array([0]=>PHP [1]=>php))
*/
$matches = array();
preg_match_all("/[,a-z]?s*(php)/i", "In my point, PHP is the web scripting language of choice. I love php", $matches, PREG_PATTERN_ORDER);
print_r($matches);
echo "
"."n";
/*
*将会输出:Array([0]=>Array([0]=>Array([0]=>, PHP [1]=>11) [1]=>Array([0]=>PHP [1]=>13)) [1]=>Array([0]=>Array([0]=>e php [1]=>63) [1]=>Array([0]=>php [1]=>65)))
*/
$matches = array();
preg_match_all("/[,a-z]?s*(php)/i", "In my point, PHP is the web scripting language of choice. I love php", $matches, PREG_SET_ORDER|PREG_OFFSET_CAPTURE);
print_r($matches);
echo "
"."n";
/*
*Array([0]=>Array([0]=>e php [1]=>63) [1]=>Array([0]=>php [1]=>65))
*/
$matches = array();
preg_match_all("/[,a-z]?s*(php)/i", "In my point, PHP is the web scripting language of choice. I love php", $matches, PREG_SET_ORDER|PREG_OFFSET_CAPTURE, 28);
print_r($matches);
echo "
"."n";
?>
3.preg_split — 通过一个正则表达式分隔字符串
array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )
通过一个正则表达式分隔给定字符串.
pattern:
用于搜索的模式,字符串形式。
subject:
输入字符串
limit:
如果指定,将限制分隔得到的子串最多只有limit个,返回的最后一个 子串将包含所有剩余部分。limit值为-1, 0或null时都代表"不限制", 作为php的标准,你可以使用null跳过对flags的设置。
flags:
flags 可以是任何下面标记的组合(以位或运算 | 组合):
PREG_SPLIT_NO_EMPTY:
如果这个标记被设置, preg_split() 将进返回分隔后的非空部分。
PREG_SPLIT_DELIM_CAPTURE:
如果这个标记设置了,用于分隔的模式中的括号表达式将被捕获并返回。
PREG_SPLIT_OFFSET_CAPTURE:
如果这个标记被设置, 对于每一个出现的匹配返回时将会附加字符串偏移量. 注意:这将会改变返回数组中的每一个元素, 使其每个元素成为一个由第0个元素为分隔后的子串,第1个元素为该子串在subject中的偏移量组成的数组。
返回值:
返回一个使用 pattern 边界分隔 subject 后得到 的子串组成的数组。
示例:
/*
*将会输出:
*Array ( [0] => In my point, [1] => is the web scripting language of choice. I love [2] => )
*/
$matches = array();
print_r(preg_split("/php/i", "In my point, PHP is the web scripting language of choice. I love php"));
echo "
"."n";
/*
*将会输出:
*Array ( [0] => In my point, [1] => is the web scripting language of choice. I love php )
*/
$matches = array();
print_r(preg_split("/php/i", "In my point, PHP is the web scripting language of choice. I love php", 2));
echo "
"."n";
/*
*将会输出:
*Array ( [0] => In my point, [1] => is the web scripting language of choice. I love )
*/
$matches = array();
print_r(preg_split("/php/i", "In my point, PHP is the web scripting language of choice. I love php", -1, PREG_SPLIT_NO_EMPTY));
echo "
"."n";
?>
4.preg_quote — Escape regular expression characters
string preg_quote ( string $str [, string $delimiter = NULL ] )
preg_quote() required The str argument adds a backslash to each character in the regular expression syntax. This is typically used when you have some runtime strings that need to be matched as regular expressions.
Regular expression special characters are: . + * ? [ ^ ] $ ( ) { } = ! < > | : -
str:
Input string
delimiter:
If the optional parameter delimiter is specified, it will also be escaped. This is typically used to escape delimiters used by PCRE functions. / is the most common delimiter.
Return value:
Returns the escaped string.
Example:
//In this example , preg_quote($word) is used to maintain the original meaning of the asterisk so that it does not use the special semantics in regular expressions.
$textbody = "This book is *very* difficult to find.";
$word = "*very*";
$textbody = preg_replace ("/" . preg_quote($word) . " /", "" . $word . "", $textbody);
//will output This book is *very* difficult to find.
echo htmlspecialchars($textbody);
?>
5.preg_grep — Returns array entries matching pattern
array preg_grep ( string $pattern , array $input [, int $flags = 0 ] )
Returns an array of elements in the given array input that match the pattern pattern.
pattern:
to search The pattern, in string form.
input:
Input array.
flags:
If set to PREG_GREP_INVERT, this function returns an array consisting of elements in the input array that do not match the given pattern pattern.
Return value:
Returns an array indexed using the key in the input.
Example:
$array = array("abc", "dd", "123", "123.22", "word123", "33.2", "0.22");
//Return all elements containing floating point numbers
//Output: Array ( [3] => 123.22 [5] => 33.2 [6] => 0.22 )
$fl_array = preg_grep("/ ^(d+)?.d+$/", $array);
print_r($fl_array);
//Return all elements containing floating point numbers
//Output: Array ( [0] => ; abc [1] => dd [2] => 123 [4] => word123 )
$fl_array = preg_grep("/^(d+)?.d+$/", $array, PREG_GREP_INVERT) ;
print_r($fl_array);
?>
6.preg_replace — Perform a regular expression search and replace
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
Search for the part of the subject that matches pattern and replace it with replacement.
pattern:
The pattern to search for. Can be a string or an array of strings. Several PCRE modifiers, including 'e' (PREG_REPLACE_EVAL), can be specified for this function.
replacement:
A string or array of strings used for replacement. If this parameter is a string and pattern is an array, then all patterns are replaced with this string. If pattern and replacement are both arrays, each pattern is replaced with the corresponding element in replacement. If there are fewer elements in replacement than in pattern, the extra pattern is replaced with an empty string. Replacement can contain back references \n or (available in PHP 4.0.4 and above) $n, the latter is preferred syntactically. Each such reference will be replaced by the text captured by the nth matching capturing subgroup. n can be 0-99, \0 and $0 represent the complete pattern matching text. The serial number counting method of capturing subgroups is: the left bracket representing the capturing subgroup is counted from left to right, starting from 1. If you want to use backslashes in replacement, you must use 4 ("\\", translator's annotation: Because this is first a PHP string, after escaping, it is two, and then it is considered by the regular expression engine is an original backslash).
When working in replacement mode and the backreference needs to be followed by another number (for example: adding an original number immediately after a matching pattern), you cannot use the syntax \1 to describe the backreference. . For example, \11 will make preg_replace() unable to understand whether you want a \1 backreference followed by an original 1, or a \11 backreference followed by nothing. The solution in this case is to use ${1}1.
This creates a separate $1 backreference, a separate source1. When the e modifier is used, this function will escape some characters (i.e.: ', ", and NULL) and then replace the backreference. When this is done, make sure that the backreference is resolved without single or double quotes. syntax error (for example: 'strlen('$1')+strlen("$2")'). Make sure it conforms to PHP's string syntax and conforms to the eval syntax, because after completing the replacement, the
engine will replace the resulting characters. The string is evaluated as PHP code using the eval method and the return value is used as the string that ultimately participates in the replacement.
subject:
The string or array of strings to be searched and replaced. If subject is an array, search and. Replacement is performed on each element of the subject, and the return value will also be an array.
limit:
The maximum number of replacements per mode is -1 (unlimited).
count:
If specified, it will be filled with the number of completed replacements.
Return value:
If subject is an array, preg_replace() returns an array, otherwise it returns a string. . If a match is found, the replaced subject is returned, otherwise the unchanged subject is returned.
Example:
Use a back reference to follow the original text:
$string = 'April 15, 2003';
/ *
*w+ character repeated one or more times
*d+ number repeated one or more times
*i ignore case
*/
$pattern = '/(w+) (d+) , (d+)/i';
/*
*$0 Complete pattern matching text
*${1}1 Pattern matching text in the first parentheses and add 1 at the end
*\3 Pattern matching text in the third parentheses
*/
$replacement = '$0:
${1}1,\3';
echo preg_replace($ pattern, $replacement, $string);
?>
Use an index-based array in preg_replace():
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
//Will output: The bear black slow jumped over the lazy dog.
echo preg_replace($patterns, $replacements, $string);
//We can get the desired results by sorting the patterns and replacement content by key.
ksort($patterns);
ksort($replacements);
//Will output: The slow black bear jumped over the lazy dog.
echo preg_replace($patterns, $replacements, $string);
Replace some values:
$patterns = array ('/(19|20)(d{2})-(d{1,2})-(d{1,2})/ ',
'/^s*{(w+)}s*=/');
$replace = array ('3/4/12', '$1 =');
echo preg_replace( $patterns, $replace, '{startDate} = 1999-5-27');
?>
Use modifier 'e':
$html_body = "
hello p>";
//Will output:
hello
echo htmlspecialchars(preg_replace("/(?)(w+)( [^>]*>)/e",
"'\1'.strtoupper('\2').'\3'",
$str = preg_replace('/ss+/', ' ', $str);
// will be changed to 'foo o'
echo $str ;
?>
echo preg_replace(array('/d/', '/s/'), '*', 'xp 4 to', -1 , $count );
//Equivalent to echo preg_replace('/d|s/', '', 'xp 4 to', -1 , $count);
echo $count; //3
?>
7.preg_replace_callback — Perform a regular expression search and replace with a callback
mixed preg_replace_callback ( mixed $pattern , callable $callback , mixed $subject [, int $limit = -1 [, int &$count ]] )The behavior of this function is equivalent to preg_replace except that you can specify a callback instead of replacement to calculate the replacement string. ().
pattern:
The pattern to search for, which can be a string or an array of strings.
callback:
A callback function that is called every time a replacement is needed. The parameters obtained by the function when called are the results matched from the subject. The callback function returns the string that actually participates in the replacement.
You may often need the callback function to be used only in one place: preg_replace_callback(). In this case, you can use anonymous functions to define an anonymous function as a callback when preg_replace_callback() is called. This way you keep all the calling information in the same place and don't pollute the function namespace with a callback function name that's not used anywhere else.
subject:
The target string or string array to be searched and replaced.
limit:
The maximum number of substitutions for each subject string for each pattern. The default is -1 (no limit).
count:
If specified, this variable will be filled with the number of times the replacement was performed. < ?php
// Increase the year in the text by one year.
$text = "April fools day is 04/01/2002n";
$text.= "Last christmas was 12/24/2001n ";
//Callback function
/**
*will output:
*April fools day is 04/01/2003
*Last christmas was 12/24/2002
*/
echo preg_replace_callback(
“|(d{2}/d{2}/)(d{4})|",
“next_year”,
“ $text);
/ /Use create_function
echo preg_replace_callback(
“|(d{2}/d{2}/)(d{4})|”,
create_function(
“$matches”,
'return $matches[1].($matches[2]+1);'
),

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,
