


Detailed explanation of regular expressions in PHP (code examples)
Objectives of this article:
1. Definition of regular expressions
2. Several basic grammars of regular expressions
(1) Definition of regular expressions
Regular expression is a logical formula for operating strings, which is to combine some specific characters into a regular string
For example:
<?php $p = '/abc123/'; $str = "abc123bbbb"; if (preg_match($p, $str)) { echo '该字符串符合这个规则'; } ?>
The above code The '/abc123/' in is a regular expression. We can see from it that /abc123/ is a string composed of characters and numbers, but these characters have their own special meanings, such as /abc123/ The rule of this regular expression is that the string starts with abc123. If any string matches this rule, it will match this expression.
(2) Several basic syntaxes of regular expressions
1. The regular matching pattern uses delimiters and metacharacters. The delimiter can be any character other than numbers, non-backslashes, and non-spaces. Common delimiters such as forward slash (/), hash symbol (#) and negation symbol (~)
For example:
/hello world/ The meaning of the expression Yes: The string starts with hello world
#^[0-9]$# The expression means: Match the numbers 0-9
~hello~ The expression means: The string contains hello
Let’s test it with code
Example 1、
/hello world/ The expression means: The string starts with hello world
<?php $p = "/hello world/"; $str = "hello world,i am a student"; if (preg_match($p, $str)) { echo '该字符串符合这个规则/hello world/<br/>'; } ?>
The running result is as follows:
This string conforms to this rule/hello world/
Change a string to see Next, do not start with hello world
<?php $p = "/hello world/"; $str = "helloworld,i am a student"; if (preg_match($p, $str)) { echo '该字符串符合这个规则/hello world/<br/>'; } ?>
The running result is:
Blank
Example 2,
#^[0-9]$# The meaning of the expression is: matching the numbers 0-9
<?php $p2 = "#^[0-9]$#"; $str2 = "3"; if (preg_match($p2, $str2)) { echo '该字符串符合这个规则"#^[0-9]$#<br/>'; } ?>
The running result is:
The The string conforms to this rule"#^[0-9]$
#Change the code and change the string to a number greater than 9 and see if it runs
<?php $p2 = "#^[0-9]$#"; $str2 = "30"; if (preg_match($p2, $str2)) { echo '该字符串符合这个规则"#^[0-9]$#<br/>'; }else{ echo '该字符串不符合这个规则"#^[0-9]$#<br/>'; } ?>
The result is:
This string does not comply with this rule"#^[0-9]$
Example 3,
~hello~ The meaning of the expression is: the string contains hello
The specific code is as follows:
<?php $p3 = "~hello~"; $str3 = "ahellobb"; if (preg_match($p3, $str3)) { echo '该字符串符合这个规则:~hello~'; }else{ echo '该字符串不符合这个规则:~hello~'; } ?>
The running result is:
The The string conforms to this rule: ~hello~
Now change the test string to not contain hello
The specific code is as follows:
<?php $p3 = "~hello~"; $str3 = "hell o"; if (preg_match($p3, $str3)) { echo '该字符串符合这个规则:~hello~'; }else{ echo '该字符串不符合这个规则:~hello~'; } ?>
The running result is:
This string does not comply with this rule: ~hello~
It can be seen that:
1, / means the beginning
2 , ^ means starting with the character after ^
3, $ means ending with the character before $
4, ~ means containing the meaning
2, if If the pattern contains a delimiter, the delimiter needs to be escaped with a backslash (\).
For example:
/https:\/\/www./ means starting with https://www.
The specific code As follows:
<?php $p = "/https:\/\/www./"; $str = "https://www.baidu.com"; if (preg_match($p, $str)) { echo '该字符串符合这个规则:/https:\/\/www./'; }else{ echo '该字符串不符合这个规则:/https:\/\/www./'; }
The running result is:
This string conforms to this rule: /https:\/\/www./
Try Change the string to not start with https://www. and see
<?php $p = "/https:\/\/www./"; $str = "http://www.baidu.com"; if (preg_match($p, $str)) { echo '该字符串符合这个规则:/https:\/\/www./'; }else{ echo '该字符串不符合这个规则:/https:\/\/www./'; }
The running result is:
This string does not comply with this rule: /https:\/\/www./
3. If the pattern contains a lot of delimiting characters, it is recommended to use other characters as delimiters, or you can use preg_quote to escape. .
Example 1,
<?php $p = "/https://www.baidu.com/a/b/index.html/"; $str = "http://www.baidu.com/a/b/index.html"; if (preg_match($p, $str)) { echo '该字符串符合这个规则:/https://www.baidu.com/a/b/index.html/'; }else{ echo '该字符串不符合这个规则:/https://www.baidu.com/a/b/index.html/'; }
The running result is:
Warning: preg_match(): Unknown modifier '/' in D:\E-class\class-code\classing\index.php on line 7
This string does not comply with this rule:/https://www.baidu.com/a/b/index.html/
So you cannot write directly at this time/Either escape as above, or proceed as follows
The specific code is as follows:
<?php $p = "https://www.baidu.com/a/b/index.html"; $p = '/'.preg_quote($p, '/').'/'; $str = "https://www.baidu.com/a/b/index.html"; if (preg_match($p, $str)) { echo '该字符串符合这个规则:/https://www.baidu.com/a/b/index.html/'; }else{ echo '该字符串不符合这个规则:/https://www.baidu.com/a/b/index.html/'; } ?>
The running result is:
This string conforms to this rule:/https://www.baidu.com/a/b/index.html/
4. Pattern modifiers can be used after the delimiter. Pattern modifiers include: i, m, s, etc.
Summary:
1. i means the size can be ignored Write
2. m means multi-line matching
3. If this modifier is set, the dot metacharacter (.) in the pattern matches all characters, including newline characters. Without this setting, newline characters are not included.
Case 1,
Practice goals:
1. i means that case can be ignored
<?php $p = "/ABc/i"; $str = "abc"; if (preg_match($p, $str)) { echo '该字符串符合这个规则:/ABc/i'; }else{ echo '该字符串不符合这个规则:/ABc/i'; } ?>
The running result is:
The string conforms to this rule:/ABc/i
Case 2,
Practice goal:
1. m means multi-line matching
The specific code is as follows:
<?php $p = "/chinese/m"; $str = "i am a chinese people,\n you alose is a chinese people"; $math = ""; if (preg_match_all($p, $str,$math)) { echo '该字符串符合这个规则:/chinese/m,匹配结果为:'; print_r($math); }else{ echo '该字符串不符合这个规则:/chinese/m'; } ?>
The running result is:
This string conforms to this rule: / chinese/m, the matching result is: Array ( [0] => Array ( [0] => chinese [1] => chinese ) )
What should be noted here is that Use preg_match_all otherwise preg_match will only match one line
接下来我们运行下效果
<?php $p = "/chinese/m"; $str = "i am a chinese people,\n you alose is a chinese people"; $math = ""; if (preg_match($p, $str,$math)) { echo '该字符串符合这个规则:/chinese/m,匹配结果为:'; print_r($math); }else{ echo '该字符串不符合这个规则:/chinese/m'; } ?>
运行结果为:
该字符串符合这个规则:/chinese/m,匹配结果为:Array ( [0] => chinese )
其实/m在此也算多此一举,因为preg_match_all就是表示多行匹配了
<?php $p = "/chinese/"; $str = "i am a chinese people,\n you alose is a chinese people"; $math = ""; if (preg_match_all($p, $str,$math)) { echo '该字符串符合这个规则,匹配结果为:'; print_r($math); }else{ echo '该字符串不符合这个规则'; } ?>
运行结果其实是一样的,结果为:
该字符串符合这个规则,匹配结果为:Array ( [0] => Array ( [0] => chinese [1] => chinese ) )
只是要知道m表示多行匹配的意思
案例三、
实践目标:
1、如果设定了此修正符,模式中的圆点元字符(.)匹配所有的字符,包括换行符。没有此设定的话,则不包括换行符。
具体代码如下:
<?php $p = "/chinese ./s"; $str = "i am a chinese \n people, you alose is a chinese good people"; $math = ""; if (preg_match_all($p, $str,$math)) { echo '该字符串符合这个规则,匹配结果为:'; print_r($math); }else{ echo '该字符串不符合这个规则'; } ?>
运行结果如下:
该字符串符合这个规则,匹配结果为:Array ( [0] => Array ( [0] => chinese [1] => chinese g ) )
说明第一个chinese 后面的字符是换行也匹配到了,这说明了s的意思就是.要包含换行符,接下来
我们去掉s,看下最终的结果
<?php $p = "/chinese ./"; $str = "i am a chinese \n people, you alose is a chinese good people"; $math = ""; if (preg_match_all($p, $str,$math)) { echo '该字符串符合这个规则,匹配结果为:'; print_r($math); }else{ echo '该字符串不符合这个规则'; } ?>
运行结果如下:
该字符串符合这个规则,匹配结果为:Array ( [0] => Array ( [0] => chinese g ) )
说明此刻只匹配到一个了,因为.不包含换行符,所以第一个chinese没有匹配到
总结:
本文主要讲解了
1、正则表达式的定义
2、正则表达式的几个基本语法
The above is the detailed content of Detailed explanation of regular expressions in PHP (code examples). For more information, please follow other related articles on the PHP Chinese website!

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

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

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,

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
