Home Backend Development PHP Tutorial PHP中正则的使用_PHP

PHP中正则的使用_PHP

Jun 01, 2016 pm 12:21 PM

正则表达式,作为一种快速、便捷的处理字符串的工具,在各种编程语言中都有着广泛的用途,通过在PHP中的一些使用,下面记录一下关于PHP中正则使用的一些技巧。

我的正则入门,是起源于网上的一篇文章[1],这篇文章由浅入深的阐述了正则使用的方法,我觉得是一个很好的入门材料,不过学成还是要靠个人,在使用的过程中,还是会不断地忘记,因此反反复复的阅读了这篇文章有四五遍,对于其中一些比较困难的知识点,甚至要用很久才能消化,但是只要能见坚持着看完,你会发现自己对于正则的运用能力就会显著提高。

正则表达式:

用于描述字符排列和匹配模式的一种语法规则。它主要用于字符串的模式分割、匹配、查找及替换操作。

PHP中的正则函数:

php中有两套正则函数,两者功能差不多,分别为:

一套是由PCRE(Perl Compatible Regular Expression)库提供的。使用“preg_”为前缀命名的函数;

一套由POSIX(Portable Operating System Interface of Unix )扩展提供的。使用以“ereg_”为前缀命名的函数;(POSIX的正则函数库,自PHP 5.3以后,就不在推荐使用,从PHP6以后,就将被移除)

由于POSIX正则即将推出历史舞台,并且PCRE和perl的形式差不多,更利于我们在perl和php之间切换,所以这里重点介绍PCRE正则的使用。

PCRE正则表达式

PCRE全称为Perl Compatible Regular Expression,意思是Perl兼容正则表达式。
在PCRE中,通常将模式表达式(即正则表达式)包含在两个反斜线“/”之间,如“/apple/”。

正则中重要的几个概念有:元字符、转义、模式单元(重复)、反义、引用和断言,这些概念都可以在文章[1]中轻松的理解和掌握。

常用的元字符(Meta-character):

元字符     说明
\A       匹配字符串串首的原子
\Z       匹配字符串串尾的原子
\b       匹配单词的边界     /\bis/   匹配头为is的字符串   /is\b/   匹配尾为is的字符串   /\bis\b/ 定界
\B       匹配除单词边界之外的任意字符   /\Bis/   匹配单词“This”中的“is”

\d     匹配一个数字;等价于[0-9]
\D     匹配除数字以外任何一个字符;等价于[^0-9]
\w     匹配一个英文字母、数字或下划线;等价于[0-9a-zA-Z_]
\W     匹配除英文字母、数字和下划线以外任何一个字符;等价于[^0-9a-zA-Z_]
\s     匹配一个空白字符;等价于[\f\t\v]
\S     匹配除空白字符以外任何一个字符;等价于[^\f\t\v]
\f     匹配一个换页符等价于 \x0c 或 \cL
                   匹配一个换行符;等价于 \x0a 或 \cJ
        匹配一个回车符等价于\x0d 或 \cM
\t     匹配一个制表符;等价于 \x09\或\cl
\v     匹配一个垂直制表符;等价于\x0b或\ck
\oNN   匹配一个八进制数字
\xNN   匹配一个十六进制数字
\cC    匹配一个控制字符

模式修正符(Pattern Modifiers):

模式修正符在忽略大小写、匹配多行中使用特别多,掌握了这一个修正符,往往能解决我们遇到的很多问题。

i     -可同时匹配大小写字母
M     -将字符串视为多行
S     -将字符串视为单行,换行符做普通字符看待,使“.”匹配任何字符
X     -模式中的空白忽略不计   
U     -匹配到最近的字符串
e     -将替换的字符串作为表达使用
格式:/apple/i匹配“apple”或“Apple”等,忽略大小写。     /i

PCRE的模式单元:

//1 提取第一位的属性
/^\d{2} ([\W])\d{2}\\1\d{4}$匹配“12-31-2006”、“09/27/1996”、“86 01 4321”等字符串。但上述正则表达式不匹配“12/34-5678”的格式。这是因为模式“[\W]”的结果“/”已经被存储。下个位置“\1”引用时,其匹配模式也是字符“/”。

当不需要存储匹配结果时使用非存储模式单元“(?:)”
例如/(?:a|b|c)(D|E|F)\\1g/ 将匹配“aEEg”。在一些正则表达式中,使用非存储模式单元是必要的。否则,需要改变其后引用的顺序。上例还可以写成/(a|b|c)(C|E|F)\2g/。

PCRE正则表达式函数:

preg_match()和preg_match_all()
preg_quote()
preg_split()
preg_grep()
preg_replace()

函数的具体使用,我们可以通过PHP手册来找到,下面分享一些平时积累的正则表达式:

    匹配action属性
    $str = '

';
    $match = '';
    preg_match_all('/\s+action=\"(?!http:)(.*?)\"\s/', $str, $match);
    print_r($match);
   
    在正则中使用回调函数
    /**
     * replace some string by callback function
     *
     */
    function callback_replace() {
        $url = 'http://esfang.house.sina.com.cn';
        $str = '
';
        $str = preg_replace ( '/(?       
        echo $str;
    }
   
    function search($url, $match){
        return $url . '/' . $match;
    }
   
    带断言的正则匹配
    $match = '';
    $str = 'xxxxxx.com.cn _fcksavedurl=""">xxxxxx.com.cn" bold font

paragraph text

';
    preg_match_all ( '/(?).*(?=)/', $str, $match );
    echo "
匹配没有属性的HTML标签中的内容:";
    print_r ( $match );

替换HTML源码中的地址   

    $form_html = preg_replace ( '/(?

最后,正则工具虽然强大,但是从效率和编写时间上来讲,有的时候可能没有explode来的更直接,对于一些紧急或者要求不高的任务,简单、粗暴的方法也许更好。
而对于preg和ereg两个系列之间的执行效率,曾看到文章说preg要更快一点,具体由于使用ereg的时候并不多,而且也要推出历史舞台了,再加个个人更偏好于PCRE的方式,所以笔者就不做比较了,熟悉的朋友可以发表下意见,谢谢。    小狼的世界

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)

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 does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

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.

See all articles