Home Backend Development PHP Tutorial The exciting basics of regular expressions in PHP (detailed explanation with illustrations)

The exciting basics of regular expressions in PHP (detailed explanation with illustrations)

Oct 18, 2021 pm 02:26 PM
php regular expression

In the previous article, I brought you "Learn to use PHP's List, each function and cooperation", which mainly explained how to use the list function and each function and what should be done between the two. When used together, I believe you have almost mastered it, so in this article we will take a look at regular expressions in PHP. I hope everyone has to help!

The exciting basics of regular expressions in PHP (detailed explanation with illustrations)

Regular expression is a logical formula, which is a "specified string" composed of some characters declared at the beginning and a combination of these characters. This The specified string is actually used to filter the string. It can be understood that when logging in as a user, we sometimes need to fill in specific data such as a verification code or phone number. At this time, we need to use regular expressions.

Although regular expressions look complicated, they are actually not difficult. Let’s take a look at them next.

The delimiters of regular expressions

#The first thing we have to learn is the delimiters of regular expressions. As the name suggests, The delimiter is a symbol that determines the boundary of a regular expression. Set a boundary, and the regular expression is within the boundary. At the same time, the delimiter of regular expressions is stipulated:

  • delimiter cannot be used, a-zA-Z0-9\ can be used, otherwise it can be used. And they must appear in pairs, with a beginning and an end.

The example is as follows:

1

2

3

$正则表达式$

%正则表达式%

/正则表达式/

Copy after login

What we need to pay attention to is that / is an escape character. When we need to match / in the regular expression, You can use \ to escape it. If you find it troublesome, you can directly use other delimiters such as:

1

$/$

Copy after login

The atoms of regular expressions

The atoms of regular expressions are regular expressions The smallest unit in the formula is what we need to match. In the integer expression we establish, there must be at least one atom.

In fact, it can be understood that all visible and invisible characters are atoms, such as spaces, carriage returns, line feeds, 0-9, punctuation marks, A-Za-z, and Chinese. These are atoms.

preg_match() function

Before talking about atoms in detail, we need to understand a function first, that ispreg_match

The preg_match() function in PHP can search and match strings based on defined regular expressions.

The syntax format is as follows:

1

preg_match ( string $正则 , string $字符串 [, array &$结果] )

Copy after login

According to $regex, which is the regular expression we defined, when matching $string, if it exists, the number of matches will be returned, and then the matching result will be placed in $In the results. If no result is found, 0 is returned.

Let’s take a look at it through an example:

1

2

3

4

5

6

7

8

9

10

11

<?php

//定义一个变量叫a,作为我们定义的正则表达式。

$a = &#39;/a/&#39;;

$b = &#39;abbcccddddeeeee&#39;;

if(preg_match($a, $b, $c)){

   echo &#39;匹配到了,结果为:&#39;;

   var_dump($c);

}else{

   echo &#39;没有匹配到&#39;;

}

?>

Copy after login

Output result:

The exciting basics of regular expressions in PHP (detailed explanation with illustrations)

As can be seen from the above example , we defined the variable a, hoping to match a, which happens to exist in $b, and the output through the if else statement was successful.

Another example:

1

2

3

4

5

6

7

8

9

10

11

<?php

//定义一个变量叫a,作为我们定义的正则表达式。

$a = &#39;/fff/&#39;;

$b = &#39;abbcccddddeeeee&#39;;

if(preg_match($a, $b, $c)){

   echo &#39;匹配到了,结果为:&#39;;

   var_dump($c);

}else{

   echo &#39;没有匹配到&#39;;

}

?>

Copy after login

Output result:

The exciting basics of regular expressions in PHP (detailed explanation with illustrations)

In the above example, we hope to match the string, but $ It does not exist in b, so there is no successful match. The if else statement outputs that the match is successful.

After knowing the basic usage of the preg_match() function, we can use it in combination with specially identified atoms.

Specially identified atoms

  • ##\d---matches a 0-9

  • \D---All characters except 0-9

  • ##\w

    ---a-zA- Z0-9_

  • ##\W-
  • --All characters except 0-9A-Za-z_

  • \s
  • ---Match all whitespace characters\n \t \r spaces

  • \S
  • ---Match all non-whitespace characters Characters

  • [ ]
  • ---Atoms in the specified range

    I will give you an example of their specific usage. Got it:

1

2

3

4

5

6

7

8

9

10

<?php

$a = &#39;/\d/&#39;;

$b = &#39;人生自古谁无4&#39;;

if(preg_match($a, $b, $c)){

   echo &#39;匹配到了,结果为:&#39;;

   var_dump($c);

}else{

   echo &#39;没有匹配到&#39;;

}

?>

Copy after login

Output result:


In the above example, the specially identified atom \d represents 0- If the number is 9, then there is a 4 in $b that needs to be matched, so the match is successful. The exciting basics of regular expressions in PHP (detailed explanation with illustrations)

1

2

3

4

5

6

7

8

9

10

<?php

$a = &#39;/\w/&#39;;

$b = &#39;人生自古谁无死&#39;;

if(preg_match($a, $b, $c)){

   echo &#39;匹配到了,结果为:&#39;;

   var_dump($c);

}else{

   echo &#39;没有匹配到&#39;;

}

?>

Copy after login

Output result:


#In the above example, the specially identified atom \w represents a-zA-Z0-9_, There is no corresponding element in variable b, so the output result is not matched. The exciting basics of regular expressions in PHP (detailed explanation with illustrations)

There is also a

[^]

character indicating characters that do not match the specified range.

The example is as follows:

1

2

3

4

5

6

7

8

9

10

<?php

$a = &#39;/[^0-9A-Za-z_]/&#39;;

$b = &#39;abbccc122333&#39;;

if(preg_match($a, $b, $c)){

   echo &#39;匹配到了,结果为:&#39;;

   var_dump($c);

}else{

   echo &#39;没有匹配到&#39;;

}

?>

Copy after login

Output result:

The exciting basics of regular expressions in PHP (detailed explanation with illustrations)

通过[^]字符匹配除0-9A-Za-z_以外的字符,未匹配到。

总结一下:

  • \w---[a-zA-Z0-9_]

  • \W---[^a-zA-Z0-9_]

  • \d---[0-9]

  • \D---[^0-9]

  • \s---[ \t\n\f\r]

  • \S---[^ \t\n\f\r]

正则表达式的元字符

在上面的示例中,我们能够看出通过匹配的话,只能匹配一个字符,但是在我们的日常使用中,通常会匹配多个字符,那这时候只通过我们的原子就不能达到我们的目的。就需要通过元字符来帮我们修饰原子,实现更多的功能。

  • *---代表匹配前面的一个原子,匹配0次或者任意多次前面的字符。

  • +---匹配一次或多次前面的一个字符

  • ?---前面的字符可有可无【可选】 有或没有

  • .---更标准一些应该把点算作原子。匹配除了\n以外的所有字符 或者。注:它的优先级最低了。

  • ^---必须要以抑扬符之后的字符串开始

  • $--- 必须要以$之前的字符结尾

  • \b---词边界

  • \B---非边界

  • {m}---有且只能出现m次

  • {n,m}---可以出现n到m次

  • {m,}---至少m次,最大次数不限制

  • ()---改变优先级或者将某个字符串视为一个整体,匹配到的数据取出来也可以使用它

接下来我们通过一些例子来实例看一下这些元字符的使用:

1

2

3

4

5

6

7

8

9

10

<?php

$a = &#39;/\d+/&#39;;

$b = "爱你10000年";

if(preg_match($a, $b, $c)){

   echo &#39;匹配到了,结果为:&#39;;

   var_dump($c);

}else{

   echo &#39;没有匹配到&#39;;

}

?>

Copy after login

输出结果:

The exciting basics of regular expressions in PHP (detailed explanation with illustrations)

通过元字符+的添加,匹配到了多次字符,\d+中d是匹配数字,+则表示最少匹配一次前面的字符。

正则表达式的模式修正符

通过原子和元字符的了解,我们已经完成了正则表达式的入门,但是这仍然不能代表正则表达式的真正实力,如果我们只希望正则表达式匹配一部分应该怎么办?有些特殊情况依然需要处理,这时候我们就要用到正则表达式的模式修正符。

下面列举一些常用的模式修正符:

  • i 模式中的字符将同时匹配大小写字母.

  • m 字符串视为多行

  • s 将字符串视为单行,换行符作为普通字符.

  • x 将模式中的空白忽略.

  • A 强制仅从目标字符串的开头开始匹配.

  • D 模式中的美元元字符仅匹配目标字符串的结尾.

  • U 匹配最近的字符串.

它的用法如下:

/正则表达式/模式修正符

接下来我们通过一些实例来看一下它的使用:

1

2

3

4

5

6

7

8

9

10

<?php 

    $a = &#39;/ABC/i&#39;;

$b = &#39;8988abc12313&#39;;

$c = &#39;11111ABC2222&#39;;

if(preg_match($a, $b, $d)){

     echo &#39;匹配到了,结果为:&#39;;

    var_dump($d); }else{

     echo &#39;没有匹配到&#39;;

     }

 ?>

Copy after login

输出结果:

The exciting basics of regular expressions in PHP (detailed explanation with illustrations)

i可以让匹配的时候同时匹配大小写,那么接下来把匹配的$b换成$c试一下,我们看一下输出结果:

1

2

3

4

5

6

7

8

9

10

<?php 

    $a = &#39;/ABC/i&#39;;

$b = &#39;8988abc12313&#39;;

$c = &#39;11111ABC2222&#39;;

if(preg_match($a, $c, $d)){

     echo &#39;匹配到了,结果为:&#39;;

    var_dump($d); }else{

     echo &#39;没有匹配到&#39;;

     }

 ?>

Copy after login

输出结果:

The exciting basics of regular expressions in PHP (detailed explanation with illustrations)

推荐学习:《PHP视频教程

The above is the detailed content of The exciting basics of regular expressions in PHP (detailed explanation with illustrations). For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

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

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)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1228
24
PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 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

See all articles