Home Backend Development PHP Tutorial PHP regular expression_PHP tutorial

PHP regular expression_PHP tutorial

Jul 13, 2016 pm 05:47 PM
linux php exist widely application regular of at present expression software

1. Introduction
At present, regular expressions have been widely used in many software, including *nix (Linux, Unix, etc.), operating systems such as HP, development environments such as PHP, C#, Java, and many application software. Regular expression shadow.         

The use of regular expressions can achieve powerful functions in a simple way. In order to be simple and effective yet powerful, the regular expression code is more difficult and not easy to learn, so it requires some effort. After getting started, it is relatively simple and effective to use it by referring to certain references.

Example: ^.+@.+\..+$

Such code has scared me away many times. Maybe many people are scared away by such code. Continuing reading this article will give you the freedom to apply code like this too.

2. History of regular expressions
The “ancestors” of regular expressions can be traced all the way back to early research on how the human nervous system works. Two neurophysiologists, Warren McCulloch and Walter Pitts, developed a mathematical way to describe these neural networks.

In 1956, a mathematician named Stephen Kleene published a paper titled "Representation of Neural Network Events" based on the early work of McCulloch and Pitts, introducing the concept of regular expressions. Regular expressions are used to describe expressions that he calls "the algebra of regular sets," hence the term "regular expression."

It was later discovered that this work could be applied to some early research using the computational search algorithms of Ken Thompson, the primary inventor of Unix. The first practical application of regular expressions was the qed editor in Unix.

The rest, as they say, is history as we all know it. Regular expressions have been an important part of text-based editors and search tools ever since.


3. Regular expression definition
Regular expression (regular expression) describes a string matching pattern, which can be used to check whether a string contains a certain substring, replace the matching substring, or extract a substring that meets a certain condition from a certain string. wait.

Regular expressions are text patterns composed of ordinary characters (such as the characters a through z) and special characters (called metacharacters). A regular expression acts as a template that matches a character pattern with a searched string.

3.1 Common characters
Consists of all those printing and non-printing characters that are not explicitly designated as metacharacters. This includes all uppercase and lowercase alphabetic characters, all numbers, all punctuation, and some symbols.

3.2 Non-printing characters

 cx  匹配由x指明的控制字符。例如,cM 匹配一个Control-M 或回车符。x 的值必须为A-Z 或a-z 之一。否则,将c 视为一个原义的'c' 字符。
f  匹配一个换页符。等价于x0c 和cL。
n  匹配一个换行符。等价于x0a 和cJ。
r  匹配一个回车符。等价于x0d 和cM。
s  匹配任何空白字符,包括空格、制表符、换页符等等。等价于[ fnrtv]。
S  匹配任何非空白字符。等价于[^ fnrtv]。
t  匹配一个制表符。等价于x09 和cI。
v  匹配一个垂直制表符。等价于x0b 和cK。


3.3 Special characters
The so-called special characters are characters with special meanings. For example, the * in "*.txt" mentioned above simply means the meaning of any string. If you want to find files with * in the file name, you need to escape the *, that is, add one in front of it. ls*.txt. Regular expressions have the following special characters.

字符
 $  匹配输入字符串的结尾位置如果设置了RegExp 对象的Multiline 属性,则$ 也匹配'n' 或'r'要匹配$ 字符本身,请使用$
()  标记一个子表达式的开始和结束位置子表达式可以获取供以后使用要匹配这些字符,请使用( 和)
*  匹配前面的子表达式零次或多次要匹配* 字符,请使用*
+  匹配前面的子表达式一次或多次要匹配+ 字符,请使用+
.  匹配除换行符n之外的任何单字符要匹配.,请使用.
[  标记一个中括号表达式的开始。要匹配[,请使用[
?  匹配前面的子表达式零次或一次,或指明一个非贪婪限定符。要匹配? 字符,请使用?
 将下一个字符标记为或特殊字符、或原义字符、或向后引用、或八进制转义符。
^  匹配输入字符串的开始位置,除非在方括号表达式中使用,此时它表示不接受该字符集合。要匹配^ 字符本身,请使用^
{  标记限定符表达式的开始。要匹配{,请使用{
|  指明两项之间的一个选择。要匹配|,请使用|

3.4 Qualifier

Qualifiers are used to specify how many times a given component of a regular expression must appear to satisfy a match. There are 6 types: * or + or ? or {n} or {n,} or {n,m}. The *, +, and ? qualifiers are all greedy in that they will match as many literals as possible. Non-greedy or minimal matching can be achieved by appending a ? after them.
The qualifiers of regular expressions are:

特别字符
 *  匹配前面的子表达式零次或多次。例如,zo* 能匹配"z" 以及"zoo"。* 等价于{0,}
+  匹配前面的子表达式一次或多次。例如,'zo+' 能匹配"zo" 以及"zoo",但不能匹配"z"。+ 等价于{1,}
?  匹配前面的子表达式零次或一次。例如,"do(es)?" 可以匹配"do" 或"does" 中的"do" 。? 等价于{0,1}
{n}  n 是一个非负整数。匹配确定的n 次。例如,'o{2}' 不能匹配"Bob" 中的'o',但是能匹配"food" 中的两个o
{n,}  n 是一个非负整数。至少匹配n 次。
{n,m}  m 和n 均为非负整数,其中n <= m。最少匹配n 次且最多匹配m 次。

3.5 Locator

Used to describe the boundary of a string or a word, ^ and $ refer to the beginning and end of the string respectively, b describes the front or back boundary of a word, and B represents a non-word boundary. Qualifiers cannot be used on locators.


3.6 Select

Use parentheses to enclose all options, and separate adjacent options with |. However, using parentheses will have a side effect, that is, related matches will be cached. In this case, you can use ?: before the first option to eliminate this side effect.
Among them, ?: is one of the non-capturing elements, and the other two non-capturing elements are ?= and ?!. These two have more meanings. The former is a forward lookup and matches the regular expression in parentheses at any beginning. The search string is matched at any position of the regular expression pattern, which is a negative lookahead that matches the search string at any initial position that does not match the regular expression pattern.

3.7 Backreferences

                                                                       ,,,,,,, adding parentheses around a regular expression pattern or part of a pattern, will cause the associated matches to be stored in a temporary buffer, with each submatch captured being encountered from left to right in the regular expression pattern. Content storage. The buffers in which submatches are stored are numbered starting from 1 and numbered consecutively up to a maximum of 99 subexpressions. Each buffer can be accessed using 'n', where n is a one- or two-digit decimal number that identifies a particular buffer.
You can use the non-capturing metacharacters '?:', '?=', or '?!' to ignore the preservation of related matches.

4. Operational precedence of various operators

Operations with the same priority are performed from left to right, and operations with different priorities are performed from high to low. The precedence of various operators from high to low is as follows:


   转义符
(), (?:), (?=), []  圆括号和方括号
*, +, ?, {n}, {n,}, {n,m}  限定符
^, $, anymetacharacter  位置和顺序
|  “或”操作


Excerpted from Lee.’s column

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478463.htmlTechArticle1. Introduction At present, regular expressions have been widely used in many software, including *nix (Linux, Unix, etc.), HP and other operating systems, PHP, C#, Java and other development environments, and many...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Unable to log in to mysql as root Unable to log in to mysql as root Apr 08, 2025 pm 04:54 PM

The main reasons why you cannot log in to MySQL as root are permission problems, configuration file errors, password inconsistent, socket file problems, or firewall interception. The solution includes: check whether the bind-address parameter in the configuration file is configured correctly. Check whether the root user permissions have been modified or deleted and reset. Verify that the password is accurate, including case and special characters. Check socket file permission settings and paths. Check that the firewall blocks connections to the MySQL server.

How to solve mysql cannot be started How to solve mysql cannot be started Apr 08, 2025 pm 02:21 PM

There are many reasons why MySQL startup fails, and it can be diagnosed by checking the error log. Common causes include port conflicts (check port occupancy and modify configuration), permission issues (check service running user permissions), configuration file errors (check parameter settings), data directory corruption (restore data or rebuild table space), InnoDB table space issues (check ibdata1 files), plug-in loading failure (check error log). When solving problems, you should analyze them based on the error log, find the root cause of the problem, and develop the habit of backing up data regularly to prevent and solve problems.

Can mysql run on android Can mysql run on android Apr 08, 2025 pm 05:03 PM

MySQL cannot run directly on Android, but it can be implemented indirectly by using the following methods: using the lightweight database SQLite, which is built on the Android system, does not require a separate server, and has a small resource usage, which is very suitable for mobile device applications. Remotely connect to the MySQL server and connect to the MySQL database on the remote server through the network for data reading and writing, but there are disadvantages such as strong network dependencies, security issues and server costs.

Solutions to the errors reported by MySQL on a specific system version Solutions to the errors reported by MySQL on a specific system version Apr 08, 2025 am 11:54 AM

The solution to MySQL installation error is: 1. Carefully check the system environment to ensure that the MySQL dependency library requirements are met. Different operating systems and version requirements are different; 2. Carefully read the error message and take corresponding measures according to prompts (such as missing library files or insufficient permissions), such as installing dependencies or using sudo commands; 3. If necessary, try to install the source code and carefully check the compilation log, but this requires a certain amount of Linux knowledge and experience. The key to ultimately solving the problem is to carefully check the system environment and error information, and refer to the official documents.

MySQL can't be installed after downloading MySQL can't be installed after downloading Apr 08, 2025 am 11:24 AM

The main reasons for MySQL installation failure are: 1. Permission issues, you need to run as an administrator or use the sudo command; 2. Dependencies are missing, and you need to install relevant development packages; 3. Port conflicts, you need to close the program that occupies port 3306 or modify the configuration file; 4. The installation package is corrupt, you need to download and verify the integrity; 5. The environment variable is incorrectly configured, and the environment variables must be correctly configured according to the operating system. Solve these problems and carefully check each step to successfully install MySQL.

How to solve the problem of missing dependencies when installing MySQL How to solve the problem of missing dependencies when installing MySQL Apr 08, 2025 pm 12:00 PM

MySQL installation failure is usually caused by the lack of dependencies. Solution: 1. Use system package manager (such as Linux apt, yum or dnf, Windows VisualC Redistributable) to install the missing dependency libraries, such as sudoaptinstalllibmysqlclient-dev; 2. Carefully check the error information and solve complex dependencies one by one; 3. Ensure that the package manager source is configured correctly and can access the network; 4. For Windows, download and install the necessary runtime libraries. Developing the habit of reading official documents and making good use of search engines can effectively solve problems.

Monitor MySQL and MariaDB Droplets with Prometheus MySQL Exporter Monitor MySQL and MariaDB Droplets with Prometheus MySQL Exporter Apr 08, 2025 pm 02:42 PM

Effective monitoring of MySQL and MariaDB databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Prometheus MySQL Exporter is a powerful tool that provides detailed insights into database metrics that are critical for proactive management and troubleshooting.

CentOS Interview Questions: Ace Your Linux System Administrator Interview CentOS Interview Questions: Ace Your Linux System Administrator Interview Apr 09, 2025 am 12:17 AM

Frequently asked questions and answers to CentOS interview include: 1. Use the yum or dnf command to install software packages, such as sudoyumininstallnginx. 2. Manage users and groups through useradd and groupadd commands, such as sudouseradd-m-s/bin/bashnewuser. 3. Use firewalld to configure the firewall, such as sudofirewall-cmd--permanent-add-service=http. 4. Set automatic updates to use yum-cron, such as sudoyumininstallyum-cron and configure apply_updates=yes.

See all articles