php 正则表达式捕获组与非捕获组
熟练掌握正则表达式是每个程序员的基础要求,对于每个初学者来说会被正则表达式一连串字符弄得头晕眼花。博主便会如此,一直对正则表达式有种莫名的恐惧。近来看到另一位博友写的 《php正则表达式》一文获益良多,对其通配符以及捕获数据两个章节颇感兴趣。这两个章节正好涉及到的是正则表达式的捕获组与非捕获组的知识,因而本文来细细探讨下这部分知识。
我们知道,在正则表达式下(x) 表示匹配'x'并记录匹配的值。这只是比较通俗的说法,甚至说这是不严谨的说法,只有()捕获组形式才会记录匹配的值。非捕获组则只匹配,不记录。
捕获组:
(pattern)
这种形式是我们见到最多的一种形式,匹配并返回捕获结果,可以嵌套,组号顺序从左到右依次排列‘。
<span style="color: #800080;">$regex</span> = '/(ab(c)+)+d(e)?/'<span style="color: #000000;">; </span><span style="color: #800080;">$str</span> = 'abccde'<span style="color: #000000;">;</span><span style="color: #800080;">$matches</span> = <span style="color: #0000ff;">array</span><span style="color: #000000;">(); </span><span style="color: #0000ff;">if</span>(<span style="color: #008080;">preg_match</span>(<span style="color: #800080;">$regex</span>, <span style="color: #800080;">$str</span>, <span style="color: #800080;">$matches</span><span style="color: #000000;">)){ </span><span style="color: #008080;">print_r</span>(<span style="color: #800080;">$matches</span><span style="color: #000000;">);}</span><span style="color: #0000ff;"><br></span>
匹配结果:
<span style="color: #0000ff;">Array</span> ( [0] => abccde [1] => abcc [2] => c [3] => e )
(?Pname>pattern)
这种方式虽然看起来在构造正则表达式的时候略微复杂一点,但实质上与(pattern)一样。最大的优势体现在对结果处理上,程序员可以直接根据自己设置的
<span style="color: #800080;">$regex</span> = '/(?P<group1>\w(?P<group2>\w))abc(?P<group3>\w)45/'<span style="color: #000000;">;</span><span style="color: #800080;">$str</span> = 'fsabcd45'<span style="color: #000000;">;</span><span style="color: #800080;">$matches</span> = <span style="color: #0000ff;">array</span><span style="color: #000000;">(); </span><span style="color: #0000ff;">if</span>(<span style="color: #008080;">preg_match</span>(<span style="color: #800080;">$regex</span>, <span style="color: #800080;">$str</span>, <span style="color: #800080;">$matches</span><span style="color: #000000;">)){ </span><span style="color: #008080;">print_r</span>(<span style="color: #800080;">$matches</span><span style="color: #000000;">);} </span></group3></group2></group1>
匹配结果:
<span style="color: #0000ff;">Array</span> ( [0] => fsabcd45 [group1] => fs [1] => fs [group2] => s [2] => s [group3] => d [3] => d )
\num
num是一个整数,是对捕获组的反向引用。 例如\2表示第二个子组匹配值,\表示第一个子组匹配值
<span style="color: #800080;">$regex</span> = '/(\w)(\w)\2\1/'<span style="color: #000000;">; </span><span style="color: #800080;">$str</span> = 'abba'<span style="color: #000000;">;</span><span style="color: #800080;">$matches</span> = <span style="color: #0000ff;">array</span><span style="color: #000000;">(); </span><span style="color: #0000ff;">if</span>(<span style="color: #008080;">preg_match</span>(<span style="color: #800080;">$regex</span>, <span style="color: #800080;">$str</span>, <span style="color: #800080;">$matches</span><span style="color: #000000;">)){ </span><span style="color: #008080;">print_r</span>(<span style="color: #800080;">$matches</span><span style="color: #000000;">);}</span>
匹配结果:
<span style="color: #0000ff;">Array</span> ( [0] => abba [1] => a [2] => b )
注意,这里我疏忽了一个小细节,一开始我第一样代码是 $regex = “/(\w)(\w)\2\1/”; 结果返回无匹配结果,经过调试后,发现这里只能用' '。'与" 用法差别大家还是需要注意下。
\k name >
了解了(?Pname>pattern)与\num,这个就不难理解了。\k是对命名捕获组的反向引用。其中 name 是捕获组名。
<span style="color: #800080;">$regex</span>='/(?P<name>\w)abc\k<name>/'<span style="color: #000000;">;</span><span style="color: #800080;">$str</span>="fabcf"<span style="color: #000000;">;</span><span style="color: #0000ff;">echo</span> <span style="color: #008080;">preg_match_all</span>(<span style="color: #800080;">$regex</span>, <span style="color: #800080;">$str</span>,<span style="color: #800080;">$matches</span><span style="color: #000000;">);</span><span style="color: #008080;">print_r</span>(<span style="color: #800080;">$matches</span>);</name></name>
匹配结果:
Array ( [0] => Array ( [0] => fabcf ) [name] => Array ( [0] => f ) [1] => Array ( [0] => f ) )
非捕获组:
(?:pattern)
与(pattern)的唯一区别是,匹配pattern但不捕获匹配结果。这里便不再举例。
还有四种方式实际上讲的是一个事情:预查。
预查分为正向预查与反向预查。根据字面理解,正向预查是判断匹配字符串后面某些字符存在与否,而反向预查则是判断匹配字符串前面某些字符存在与否。
正向预查判断存在使用(?=pattern),判断不存在使用(?!pattern)。
反向预查判断存在使用(?pattern),判断不存在使用(?pattern)。
<span style="color: #800080;">$regx</span>='/(?;<span style="color: #800080;">$str</span>="abcd ebcd abce ebca"<span style="color: #000000;">;</span><span style="color: #0000ff;">if</span>(<span style="color: #008080;">preg_match_all</span>(<span style="color: #800080;">$regx</span>, <span style="color: #800080;">$str</span>, <span style="color: #800080;">$matches</span><span style="color: #000000;">)){ </span><span style="color: #008080;">print_r</span>(<span style="color: #800080;">$matches</span><span style="color: #000000;">);}</span>
匹配结果:
<span style="color: #0000ff;">Array</span> ( [0] => <span style="color: #0000ff;">Array</span> ( [0] => bc) )
这四种形式使用的是否只要注意好相对匹配字符串的位置和断言肯定还是否定,就会很快掌握。
另外,预查的四种形式是零宽度的,匹配的时候只做一个判断,本身是不占位置的。/HE(?=L)LLO/ 与HELLO匹配,而/HE(?=L)LO/与HELLO是不匹配的。毕竟但从字节数上两者就是不匹配的,前者只有4个,而后者有5个。

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools
