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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.