Home php教程 php手册 php中正则表达式的子模式详解

php中正则表达式的子模式详解

Jun 13, 2016 am 09:56 AM
php about article have model regular of expression Detailed explanation need

文章介绍了关于php中正则表达式的子模式详解,有需要知道php中正则表达式的子模式的朋友可参考一下。

函数
mixed preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit])

功能
在 subject 中搜索 pattern 模式的匹配项并替换为 replacement。如果指定了 limit,则仅替换 limit 个匹配,如果省略 limit 或者其值为 -1,则所有的匹配项都会被替换。
replacement可以包含\n形式或$n形式的逆向引用,n可以为0到99,\n表示匹配pattern第n个子模式的文本,\0表示匹配整个pattern的文本。

子模式
$pattern参数中被圆括号括起来的正则表达式,子模式的数目即从左到右圆括号的数目。(pattern即模式)

首先,我们先看一段PHP代码:

 代码如下 复制代码

    $time = date ("Y-m-d H:i:s");
    $pattern = "/d{4}-d{2}-d{2} d{2}:d{2}:d{2}/i";
    if(preg_match($pattern,$time,$arr)){
    echo "
";<br>
    print_r($arr);        <br>
    echo "
Copy after login
Copy after login
";
    }
?>

显示结果:

Array
(
    [0] => 2012-06-23 03:08:45
)有没有注意到,显示的结果只有一条数据,即符合匹配模式的时间格式,那如果只有一条记录的话,为什么还要用数组保存呢?直接使用字符串保存不是更好?

带着这个问题,我们来看下正则表达式中的子模式。

在正则表达式中,可以使用“(”和“)”将模式中的子字符串括起来,以形成一个子模式。将子模式视为一个整体时,那么它就相当于一个单个字符。

比如,我们将以上的代码稍微修改下,改成如下:

 

 代码如下 复制代码

    $time = date ("Y-m-d H:i:s");
    $pattern = "/(d{4})-(d{2})-(d{2}) (d{2}):(d{2}):(d{2})/i";
    if(preg_match($pattern,$time,$arr)){
    echo "
";<br>
    print_r($arr);        <br>
    echo "
Copy after login
Copy after login
";
    }
?>

注意:我只修改了$pattern,在匹配模式中,使用了括号()

执行结果:


Array
(
    [0] => 2012-06-23 03:19:23
    [1] => 2012
    [2] => 06
    [3] => 23
    [4] => 03
    [5] => 19
    [6] => 23
)
总结:我们可以使用小括号给整个匹配模式进行分组,默认情况下,每个分组会自动拥有一个组号,规则是,从左到右,以分组的左括号为标志,第一个出现的分组为组号1,第二个为组号2,以此类推。其中,分组0对应整个正则表达式。对整个正则匹配模式进行了分组以后,就可以进一步使用“向后引用”来重复搜索前面的某个分组匹配的文本。例如:1代表分组1匹配的文本,2代表分组2匹配的文本等等我们可以进一步修改下代码,如下所示:

 代码如下 复制代码
    $time = date ("Y-m-d H:i:s");
    $pattern = "/(d{4})-(d{2})-(d{2}) (d{2}):(d{2}):(d{2})/i";
    $replacement = "$time格式为:$0
替换后的格式为:\1年\2月\3日 \4时\5分\6秒";
    print preg_replace($pattern, $replacement, $time);
    if(preg_match($pattern,$time,$arr)){
        echo "
";<br>
        print_r($arr);        <br>
        echo "
Copy after login
";
    }
?>

 

注意:

因为是在双引号中,所以使用分组的时候应该使用两个反斜杠,如:\1,而如果在单引号中,则使用一个反斜杠就可以了,如:1
\1用于捕获分组一种的内容:2012,\6用于捕获分组6中的内容          
执行结果:


$time格式为:2012-06-23 03:30:31
替换后的格式为:2012年06月23日 03时30分31秒
Array
(
    [0] => 2012-06-23 03:30:31
    [1] => 2012
    [2] => 06
    [3] => 23
    [4] => 03
    [5] => 30
    [6] => 31
)

高级正则表达式

  除了 POSIX BRE 和 ERE 之外,libutilitis 还支持与TCL 8.2兼容的高级正则表达式语
  法(ARE)。 通过为 stRegEx 参数增加前缀 "***:" 就可以开启 ARE 模式,这个前缀覆
  盖 bExtended 选项。基本上讲,ARE 是 ERE 的超集。 它在 ERE 的基础上进行了如下几
  项扩展:

  1. 支持"懒惰匹配"(也叫"非贪婪匹配"或"最短匹配"):在 '?', '*', '+' 或 '{m,n}'
     后追加 '?' 符号就可以启用最短匹配,使得该正则表达式子句在满足条件的前提下匹
     配尽可能少的字符(默认是匹配尽可能多的字符)。例如:将 "a.*b" 作用于 "abab"
     时,将匹配整个串("abab"),若使用 "a.*?b",则将只匹配前两个字符("ab")。

  2. 支持子表达式的向前引用匹配:在 stRegEx 中,可以使用 'n' 向前引用曾经定义的
     子表达式。如:"(a.*)1" 可匹配 "abcabc" 等。

  3. 无名子表达式:使用 "(?:表达式)" 的方式创建一个无名表达式, 无名表达式不返回
     到一个 'n' 匹配。

  4. 向前预判:要命中匹配,必须向前满足指定条件。 向前预判分为肯定预判和否定预判
     两种。肯定预判的语法为:"(?=表达式)",例如:"bai.*(?=yang)" 匹配 "bai yang"
     中的前四个字符("bai "),但在匹配时保证字符串在 "bai.*" 后必须包含 "yang".
     否定判断的语法为:"(?!表达式)", 例如:"bai.*(?!yang)" 匹配 "bai shan" 的前
     四个字符,但在匹配是保证字符串在 "bai.*" 后不出现 "yang"。

  5. 支持模式切换前缀,在 "***:" 之后可以紧跟形如 "(?模式串)" 样式的模式串,模式
     串影响其后表达式的语义和行为。模式串可以是一下字符的组合:

     b - 切换至 POSIX BRE 模式,覆盖 bExtended 选项。
     e - 切换至 POSIX ERE 模式,覆盖 bExtended 选项。
     q - 切换至文本字面匹配模式, 表达式中的字符都作为文本进行搜索,取消一切正则
         语义。此模式将正则匹配退化为一次简单字符串查找。"***=" 前缀是其快捷表示
         方式,意即:"***=" 等同于 "***:(?q)"。

     c - 执行大小写敏感的匹配,覆盖 bNoCase 选项。
     i - 执行忽略大小写的匹配,覆盖 bNoCase 选项。

     n - 开启行敏感的匹配:'^' 和 '$' 匹配行首和行尾;'.' 和否定集('[^...]')不
         匹配换行符。此功能等同于 'pw' 模式串。覆盖 bNewLine 选项。
     m - 等同于 'n'。
     p - '^' 和 '$' 只匹配整个字符串的首尾,不匹配行;'.' 和否定集不匹配换行符。
         覆盖 bNewLine 选项。
     w - '^' 和 '$' 匹配行首和行尾;'.' 和否定集匹配换行符。覆盖 bNewLine 选项。
     s - '^' 和 '$' 只匹配整个字符串的首尾,不匹配行;'.' 和否定集匹配换行符。覆
         盖 bNewLine 选项。ARE 状态下默认使用此模式。

     x - 开启扩展模式:在扩展模式中,将忽略表达式中的空白符和注释符 '#' 后的内容
         例如:
         @code@
   (?x)
   s+ ([[:graph:]]+)      # first number
   s+ ([[:graph:]]+)      # second number
         @code@
         等同于 "s+([[:graph:]]+)s+([[:graph:]]+)"。
     t - 关闭扩展模式,不忽略空白符和注释符后的内容。ARE 状态下默认使用此模式。

  6. 与 BRE/ERE 模式不同的 Perl 风格字符类换码序列:

 perl类    等效POSIX表达式   描述
    ----------------------------------------------------------------------------
 a        -                 响铃字符
 A        -                 不论当前模式如何,仅匹配整个串的最开头
 b        -                 退格字符 ('x08')
 B        -                 转义字符本身 ('\')
 cX       -                 控制符-X (= X & 037)
 d        [[:digit:]]       10 进制数字 ('0' - '9')
 D        [^[:digit:]]      非数字
 e        -                 退出符 ('x1B')
 f        -                 换页符 ('x0C')
 m        [[:<:>  M        [[:>:]]           单词结束位置
 n        -                 换行符 ('x0A')
 r        -                 回车符 ('x0D')
 s        [[:space:]]       空白符
 S        [^[:space:]]      非空白符
 t        -                 制表符 ('x09')
 uX       -                 16 位 UNICODE 字符 (X∈[0000 .. FFFF])
 UX       -                 32 位 UNICODE 字符 (X∈[00000000 .. FFFFFFFF])
 v        -                 纵向制表符 ('x0B')
 w        [[:alnum:]_]      组成单词的字符
 W        [^[:alnum:]_]     非单词字符
 xX       -                 8 位字符 (X∈[00 .. FF])
 y        -                 单词边界(m 或 M)
 Y        -                 非单词边界
 Z        -                 不论当前模式如何,仅匹配整个串的最尾部
         -                 NULL,空字符
 X        -                 子表达式向前引用 (X∈[1 .. 9])
 XX       -                 子表达式向前引用或 8 进制表示的 8 字符
 XXX      -                 子表达式向前引用或 8 进制表示的 8 字符
 

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)

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

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

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

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

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,

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

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.

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.

See all articles