search
HomeBackend DevelopmentPHP TutorialDetailed explanation of regular expression examples in PHP

Detailed explanation of regular expression examples in PHP

May 23, 2018 pm 03:04 PM
phpexpressionDetailed explanation

在编程里基本都会用到正则表达式来处理数据,那么下面就具体在PHP中怎么运用吧,本文通过具体的实例,给大家讲解了PHP中正则表达式的使用方法。

最近使用 PHP 写了一个应用,主要是正则表达式的处理,趁机系统性的学习了相应知识。
这篇文章的写作方式不是讲理论,而是通过具体的例子来了解正则,这样也更有实践性,在此基础上再去看正则表达式的基本概念会更有收获。

禁止分组的捕获

在正则中分组很有用,可以定义子模式,然后可以通过后向引用来引用分组的内容,但是有的时候仅仅想通过分组来进行范围定义,而不想被分组来捕获,通过一个例子就能明白:

$str = "http://www.google.com";
$preg= "/http:\/\/\w+\.\w+.(?:net|com|cn)+/is";
$preg2= "/http:\/\/\w+\.\w+.(net|com|cn)+/is";
preg_match($preg,$str,$arr);
preg_match($preg2,$str,$arr2);

当模式中出现?:表示这个括号的分组不会被引用,运行下例子就能明白。

preg_match() 和 preg_match_all() 的区别

preg_match() 在匹配模式的时候匹配到一次就结束,而 preg_match_all() 则进行全局匹配,通过一个例子就能明白:

$str='hello world china';
$preg="/\w+\s/is";
preg_match($preg,$str,$arr);
print_r($arr);
preg_match_all($preg,$str,$arr);
print_r($arr);

正确理解 $ 和 ^

先说一个正则,为了匹配是否是手机号:

$str = "13521899942a";
$preg="/1[\d]{3,15}/is";
if (preg_match($preg,$str,$arr)) {
  echo "ok";
}

虽然字符串中有一个英文字母,但是这个子模式却匹配了,原因就在于模式匹配到后就结束了,不会再去寻找英文字母,为了解决这问题 $ 和 ^ 就发挥作用了,比如让字符串的开始和结尾必须匹配一定的模式,修改如下:

$str = "13521899942a";
$preg="/1[\d]{3,15}$/is";
if (preg_match($preg,$str,$arr)) {
  echo "ok";
}

$ 和 ^ 的跨行模式

默认的情况下,$ 和 ^ 只会匹配完整段落的开始和结尾,但是通过改变选项,允许匹配文本的每一行的开始和结尾,通过下面的例子就能明白

$str='hello
world';
$preg='/\w+$/ism';//$preg='/(?m)\w+$/is';
preg_match_all($preg,$str,$arr);
print_r($arr);

分组命名

在正则中通过括号分组后,可以使用 \1,\2 这样的数字进行后向引用,但是假如正则中模式太多,在使用的时候就会比较混乱,这时候可以采用分组命名来进行引用,看个例子:

$str ="email:ywdblog@gmail.com;";
preg_match("/email:(?<email>\w+?)/is", $str, $matches);
echo $matches["email"] . "_" . $matches[&#39;no&#39;];

懒惰模式

正则在匹配的时候是贪婪的,只要符合模式就会一直匹配下去,下面的例子,匹配到的文本是

hello

world


$str = "<h2 id="hello">hello</h2><h2 id="world">world</h2>";
$preg = "/<h2>.*<\/h2>/is";
preg_match($preg,$str,$arr);
print_r($arr);

通过改变一个选项可以修改为懒惰模式,就是一旦匹配到就中止,修改代码如下:

$str = "<h2 id="hello">hello</h2><h2 id="world">world</h2>";
$preg = "/<h2>.*?<\/h2>/is";
preg_match($preg,$str,$arr);
print_r($arr);

进一步理解 preg_match_all()

通过这函数的最后一个参数,能够返回不同形式的数组:

$str= &#39;jiangsu (nanjing) nantong
guangdong (guangzhou) zhuhai
beijing (tongzhou) haidian&#39;;
$preg = &#39;/^\s*+([^(]+?)\s\(([^)]+)\)\s+(.*)$/m&#39;;
preg_match_all($preg,$str,$arr,PREG_PATTERN_ORDER);
print_r($arr);
preg_match_all($preg,$str,$arr,PREG_SET_ORDER);
print_r($arr);

强大的正则替换回调

虽然 preg_replace() 函数能完成大多数的替换,但是假如你想更好的控制,可以使用回调,不用多说看例子:

$str = "china hello world";
$preg = &#39;/\b(\w+)(\w)\b/&#39;;
function fun($m){
    return $m[1].strtoupper($m[2]);
}
echo preg_replace_callback($preg,"fun",$str);

在这一点上,PHP 比 Python 强大的多,Python 中没有正则回调,不过可以使用闭包的方式解决,可看我以前的文章。

preg_quote()

这个函数类似于 Python 中的 re.compile() 函数,假如在模式中一些元字符仅仅想表达字符的本身含义,可以转义,但是假如在模式中写太多的转义,会显得很混乱,可以使用这个函数来统一转义:

$str = &#39;\\*china*world&#39;;
$preg = "\*china";
$preg = preg_quote($preg);
echo $preg;
preg_match( "/{$preg}/is",$str,$arr);
print_r($arr);

向前查找 ?= 的妙用

用英文解释可能比较贴切:

The "?=" combination means "the next text must be like this". This construct doesn't capture the text.
(1)这个例子可以获取 URL 中的协议部分,比如 https,ftp,注意 ?: 后面的部分不在返回的内容中。

$str = "http://www.google.com";
$str = "https://www.google.com";
$preg = &#39;/[a-z]+(?=:)/&#39;;
preg_match($preg,$str,$arr);
print_r($arr);

(2)"invisible" 分隔符

也叫 “zero-width” 分隔符,参考下面的例子:

$str = ("chinaWorldHello");
$preg = "/(?=[A-Z])/";
$arr = preg_split($preg,$str);
print_r($arr);

(3)匹配强密码

instead of specifying the order that things should appear, it's saying that it must appear but we're not worried about the order.
The first grouping is (?=.{8,}). This checks if there are at least 8 characters in the string. The next grouping (?=.[0-9]) means "any alphanumeric character can happen zero or more times, then any digit can happen". So this checks if there is at least one number in the string. But since the string isn't captured, that one digit can appear anywhere in the string. The next groupings (?=.[a-z]) and (?=.[A-Z]) are looking for the lower case and upper case letter accordingly anywhere in the string.

$str= "HelloWorld2016";
if (preg_match("/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/", $str,$arr)){
  print_r($arr);
}

向后查找 ?

??= 表示假如匹配到特定字符,则返回该字符前面的内容。

$str = &#39;chinadhello&#39;;
$preg = &#39;/(?<=a)d(?=h)/&#39;;  
preg_match($preg, $str, $arr);
print_r($arr);

以上就是本文的全部内容,希望对大家的学习有所帮助。


相关推荐:

PHP的PDO常用类库实例分析_php技巧

非常有用的9个PHP代码片段_php技巧

thinkphp框架下实现登录、注册、找回密码功能_php技巧

The above is the detailed content of Detailed explanation of regular expression examples in PHP. 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
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 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 vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 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

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.