search
HomeBackend DevelopmentPHP TutorialDetailed 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 = &#39;/abc123/&#39;;
$str = "abc123bbbb";
if (preg_match($p, $str)) {
    echo &#39;该字符串符合这个规则&#39;;
}
?>

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 &#39;该字符串符合这个规则/hello world/<br/>&#39;;
}

?>

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 &#39;该字符串符合这个规则/hello world/<br/>&#39;;
}

?>

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 &#39;该字符串符合这个规则"#^[0-9]$#<br/>&#39;;
}
?>

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 &#39;该字符串符合这个规则"#^[0-9]$#<br/>&#39;;
}else{
    echo &#39;该字符串不符合这个规则"#^[0-9]$#<br/>&#39;;
}
?>

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 &#39;该字符串符合这个规则:~hello~&#39;;
}else{
    echo &#39;该字符串不符合这个规则:~hello~&#39;;
}
?>

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 &#39;该字符串符合这个规则:~hello~&#39;;
}else{
    echo &#39;该字符串不符合这个规则:~hello~&#39;;
}
?>

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 &#39;该字符串符合这个规则:/https:\/\/www./&#39;;
}else{
    echo &#39;该字符串不符合这个规则:/https:\/\/www./&#39;;
}

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 &#39;该字符串符合这个规则:/https:\/\/www./&#39;;
}else{
    echo &#39;该字符串不符合这个规则:/https:\/\/www./&#39;;
}

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 &#39;该字符串符合这个规则:/https://www.baidu.com/a/b/index.html/&#39;;
}else{
    echo &#39;该字符串不符合这个规则:/https://www.baidu.com/a/b/index.html/&#39;;
}

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 = &#39;/&#39;.preg_quote($p, &#39;/&#39;).&#39;/&#39;;
$str = "https://www.baidu.com/a/b/index.html";
if (preg_match($p, $str)) {
    echo &#39;该字符串符合这个规则:/https://www.baidu.com/a/b/index.html/&#39;;
}else{
    echo &#39;该字符串不符合这个规则:/https://www.baidu.com/a/b/index.html/&#39;;
}
?>

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 &#39;该字符串符合这个规则:/ABc/i&#39;;
}else{
    echo &#39;该字符串不符合这个规则:/ABc/i&#39;;
}
?>

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 &#39;该字符串符合这个规则:/chinese/m,匹配结果为:&#39;;
    print_r($math);
}else{
    echo &#39;该字符串不符合这个规则:/chinese/m&#39;;
}
?>

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 &#39;该字符串符合这个规则:/chinese/m,匹配结果为:&#39;;
    print_r($math);
}else{
    echo &#39;该字符串不符合这个规则:/chinese/m&#39;;
}
?>

运行结果为:

该字符串符合这个规则:/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 &#39;该字符串符合这个规则,匹配结果为:&#39;;
    print_r($math);
}else{
    echo &#39;该字符串不符合这个规则&#39;;
}

?>

运行结果其实是一样的,结果为:

该字符串符合这个规则,匹配结果为: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 &#39;该字符串符合这个规则,匹配结果为:&#39;;
    print_r($math);
}else{
    echo &#39;该字符串不符合这个规则&#39;;
}
?>

运行结果如下:

该字符串符合这个规则,匹配结果为: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 &#39;该字符串符合这个规则,匹配结果为:&#39;;
    print_r($math);
}else{
    echo &#39;该字符串不符合这个规则&#39;;
}
?>

运行结果如下:

该字符串符合这个规则,匹配结果为: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!

Statement
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
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

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 vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

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: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.