


Detailed explanation of sub-patterns of regular expressions in php_PHP tutorial
The article introduces a detailed explanation of the sub-patterns of regular expressions in PHP. Friends who need to know the sub-patterns of regular expressions in PHP can refer to it.
Function
mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit])
Function
Search subject for a match of pattern and replace with replacement. If limit is specified, only limit matches are replaced; if limit is omitted or has a value of -1, all matches are replaced.
Replacement can contain a reverse reference in the form of n or $n. n can be from 0 to 99. n represents the text matching the nth sub-pattern of pattern.
The regular expression enclosed in parentheses in the $pattern parameter, the number of sub-patterns is the number of parentheses from left to right. (pattern is pattern)
The code is as follows | Copy code |
代码如下 | 复制代码 |
$time = date ("Y-m-d H:i:s"); $pattern = "/d{4}-d{2}-d{2} d{2}:d{2}:d{2}/i"; if(preg_match($pattern,$time,$arr)){ echo " ";<br> print_r($arr); <br> echo ""; } ?> |
$pattern = "/d{4}-d{2}-d{2} d{2}:d{2}:d{2}/i";
If(preg_match($pattern,$time,$arr)){echo "
";<br> Print_r($arr); <br> echo "";
} ?>
Display results:
Array
(
[0] => 2012-06-23 03:08:45) Have you noticed that the displayed result only has one piece of data, which is the time format that matches the matching pattern? So if there is only one record, why should it be saved in an array? Wouldn't it be better to save it directly as a string?
代码如下 | 复制代码 |
$time = date ("Y-m-d H:i:s"); $pattern = "/(d{4})-(d{2})-(d{2}) (d{2}):(d{2}):(d{2})/i"; if(preg_match($pattern,$time,$arr)){ echo " ";<br> print_r($arr); <br> echo ""; } ?> |
The code is as follows | Copy code |
"; Print_r($arr); echo ""; } ?> |
Note: I only modified $pattern. In the matching pattern, I used brackets ()
Execution result:
Array
(
[0] => 2012-06-23 03:19:23
[1] => 2012
[2] => 06
[3] => 23
[4] => 03
[5] => 19
[6] => 23
)
Summary: We can use parentheses to group the entire matching pattern. By default, each group will automatically have a group number. The rule is, from left to right, with the left parenthesis of the group as the mark, the first group that appears The first one is group number 1, the second one is group number 2, and so on. Among them, group 0 corresponds to the entire regular expression. After the entire regular matching pattern is grouped, you can further use "backward reference" to repeatedly search for text matching a previous group. For example: 1 represents the text matched by group 1, 2 represents the text matched by group 2, etc. We can further modify the code as follows:
The code is as follows | Copy code |
代码如下 | 复制代码 |
$time = date ("Y-m-d H:i:s"); $pattern = "/(d{4})-(d{2})-(d{2}) (d{2}):(d{2}):(d{2})/i"; $replacement = "$time格式为:<🎜> 替换后的格式为:1年2月3日 4时5分6秒"; print preg_replace($pattern, $replacement, $time); if(preg_match($pattern,$time,$arr)){ echo " ";<br> print_r($arr); <br> echo ""; } ?> |
The replaced format is: February 3, 1 year, 4 hours, 5 minutes and 6 seconds"; Print preg_replace($pattern, $replacement, $time); If(preg_match($pattern,$time,$arr)){ echo "
"; print_r($arr); echo ""; } ?>
Note:
Because it is in double quotes, you should use two backslashes when using grouping, such as: 1, and if it is in single quotes, use one backslash, such as: 1
1 is used to capture the content of group one: 2012, 6 is used to capture the content of group 6
Execution result:
The format of $time is: 2012-06-23 03:30:31
The replaced format is: June 23, 2012 03:30:31
Array
(
[0] => 2012-06-23 03:30:31
[1] => 2012
[2] => 06
[3] => 23
[4] => 03
[5] => 30
[6] => 31
)
Advanced Regular Expressions
In addition to POSIX BRE and ERE, libutilitis also supports advanced regular expression languages compatible with TCL 8.2
Law (ARE). ARE mode can be enabled by adding the prefix "***:" to the stRegEx parameter. This prefix replaces
Cover bExtended option. Basically, ARE is a superset of ERE. It performs the following steps based on ERE
Item extension:
1. Support "lazy matching" (also called "non-greedy matching" or "shortest matching"): in '?', '*', '+' or '{m,n}'
You can enable shortest matching by appending the '?' symbol after , so that the regular expression clause matches
if the conditions are met.
Match as few characters as possible (the default is to match as many characters as possible). For example: apply "a.*b" to "abab"
When "a.*?b" is used, it will match the entire string ("abab"). If "a.*?b" is used, it will only match the first two characters ("ab").
2. Supports forward reference matching of subexpressions: In stRegEx, you can use 'n' to forward reference a previously defined
Subexpression. For example: "(a.*)1" can match "abcabc" etc.
3. Unnamed subexpression: Use "(?:expression)" to create an unnamed expression. The unnamed expression does not return
to an 'n' match.
4. Forward prediction: To hit a match, the specified conditions must be met forward. Forward prediction is divided into positive prediction and negative prediction
There are two kinds. The syntax for positive prediction is: "(?=expression)", for example: "bai.*(?=yang)" matches "bai yang"
The first four characters ("bai ") in , but when matching, ensure that the string must contain "yang".
after "bai.*"
The syntax for negative judgment is: "(?!expression)", for example: "bai.*(?!yang)" matches the first
of "bai shan"
Four characters, but when matching, it is ensured that "yang" does not appear after "bai.*" in the string.
5. Support mode switching prefix, "***:" can be followed by a pattern string in the form of "(?pattern string)", pattern
The string affects the semantics and behavior of subsequent expressions. The pattern string can be a combination of the following characters:
b - Switch to POSIX BRE mode, overriding the bExtended option.
e - Switch to POSIX ERE mode, overriding the bExtended option.
q - Switch to text literal matching mode, the characters in the expression are searched as text, and all regular expressions are canceled
Semantics. This mode reduces regular matching to a simple string search. "***=" prefix is its shortcut representation
Method, meaning: "***=" is equivalent to "***:(?q)".
c - Perform case-sensitive matching, overrides the bNoCase option.
i - performs a case-ignoring match, overrides the bNoCase option.
n - Enable line-sensitive matching: '^' and '$' match the beginning and end of the line; '.' and negation sets ('[^...]') do not
Matches newline characters. This functionality is equivalent to the 'pw' pattern string. Override the bNewLine option.
m - Same as 'n'.
p - '^' and '$' only match the beginning and end of the entire string, not lines; '.' and the negative set do not match newlines.
Overrides the bNewLine option.
w - '^' and '$' match the beginning and end of the line; '.' and the negative set match newlines. Override the bNewLine option.
s - '^' and '$' only match the beginning and end of the entire string, not lines; '.' and the negative set match newlines. Reply
Cover bNewLine option. This mode is used by default in ARE state.
x - Turn on extended mode: In extended mode, whitespace characters and content after the comment character '#' in the expression will be ignored
For example:
@code@
(?x)
s+ ([[:graph:]]+) # first number
s+ ([[:graph:]]+) # second number
@code@
Equivalent to "s+([[:graph:]]+)s+([[:graph:]]+)".
T -Close the extension mode without ignoring the content of the blank and notes. This mode is used by default in ARE state.
6. Perl-style character class escape sequence different from BRE/ERE mode:
perl class Equivalent POSIX expression Description
-------------------------------------------------- --------------------------
a - Bell character
A - No matter what the current mode is, only the beginning of the entire string is matched
b - Backspace character ('x08')
B - The escape character itself ('')
cX - Control symbol-X (= X & 037)
D [[: Digit:]] 10 -in -made numbers ('0' -'9')
D [^[:digit:]]
e - Exit character ('x1B')
f - Form feed ('x0C')
m [[:<:]] Word starting position
M [[:>:]] Since
n - Newline character ('x0A')
r - Carriage return character ('x0D')
s [[:space:]]
S [^[:space:]]
t Tab character ('x09')
uX - 16-bit UNICODE characters (X∈[0000 .. FFFF])
UX - 32-bit UNICODE characters (X∈[00000000 .. FFFFFFFF])
v - Vertical tab character ('x0B')
w [[:alnum:]_] Characters that make up words
W [^[:alnum:]_] Non-word characters
xX - 8-bit characters (X∈[00 .. FF])
y - Word boundary (m or M)
Y - Non-word boundary
Z - No matter what the current mode is, only the last
of the entire string is matched.
- NULL, empty character
X - Subexpression forward reference (X∈[1 .. 9])
XX - Subexpression forward reference or 8-character octal representation
XXX - Subexpression forward reference or 8-character octal representation

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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 is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
