Home Backend Development PHP Tutorial (转)PHP正则表述的几则使用技巧

(转)PHP正则表述的几则使用技巧

Jun 13, 2016 am 10:49 AM
match nbsp pcre php

(转)PHP正则表达的几则使用技巧
转自:http://jianzhong5137.blog.163.com/blog/static/982904920106149583449/

PHP正则表达式主要用于字符串的模式分割、匹配、查找及替换操作。使用正则表达式在某些简单的环境下可能效率不高,因此如何更好的使用PHP正则表达式需要综合考虑。

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

PHP正则表达式的定义:

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

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 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
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.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

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

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 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 and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles