


PHP regular expression introductory tutorial (recommended), regular expression introductory tutorial_PHP tutorial
Jul 12, 2016 am 08:52 AMPHP正則表達(dá)式入門教程(推薦),正則表達(dá)式入門教程
思維導(dǎo)圖
點(diǎn)擊下圖,可以看具體內(nèi)容!
介紹
正則表達(dá)式,大家在開發(fā)中應(yīng)該是經(jīng)常用到,現(xiàn)在很多開發(fā)語言都有正則表達(dá)式的應(yīng)用,比如javascript,java,.net,php等等,我今天就把我對正則表達(dá)式的理解跟大家嘮嘮,不當(dāng)之處,請多多指教!
定位
我們什么時候使用正則表達(dá)式呢?不是所有的字符操作都用正則就好了,php在某些方面用正則反而影響效率。當(dāng)我們遇到復(fù)雜文本數(shù)據(jù)的解析時候,用正則是比較好的選擇。
優(yōu)點(diǎn)
正則表達(dá)式在處理復(fù)雜字符操作的時候,可以提高工作效率,也在一定程度節(jié)省你的代碼量。
缺點(diǎn)
我們在使用正則表達(dá)式的時候,復(fù)雜的正則表達(dá)式會加大代碼的復(fù)雜度,讓人很難理解。所以我們有的時候需要在正則表達(dá)式內(nèi)部添加注釋。
通用模式
¤ 定界符,通常使用 "/"做為定界符開始和結(jié)束,也可以使用"#"。
什么時候使用"#"呢?一般是在你的字符串中有很多"/"字符的時候,因?yàn)檎齽t的時候這種字符需要轉(zhuǎn)義,比如uri。
使用"/"定界符的代碼如下.
$regex = '/^http:\/\/([\w.]+)\/([\w]+)\/([\w]+)\.html$/i'; $str = 'http://www.youku.com/show_page/id_ABCDEFG.html'; $matches = array(); if(preg_match($regex, $str, $matches)){ var_dump($matches); } echo "\n";
preg_match中的$matches[0]將包含與整個模式匹配的字符串。
使用"#"定界符的代碼如下.這個時候?qū)?/"就不轉(zhuǎn)義!
$regex = '#^http://([\w.]+)/([\w]+)/([\w]+)\.html$#i'; $str = 'http://www.youku.com/show_page/id_ABCDEFG.html'; $matches = array(); if(preg_match($regex, $str, $matches)){ var_dump($matches); } echo "\n";
¤ 修飾符:用于改變正則表達(dá)式的行為。
我們看到的('/^http:\/\/([\w.]+)\/([\w]+)\/([\w]+)\.html/i')中的最后一個"i"就是修飾符,表示忽略大小寫,還有一個我們經(jīng)常用到的是"x"表示忽略空格。
貢獻(xiàn)代碼:
$regex = '/HELLO/'; $str = 'hello word'; $matches = array(); if(preg_match($regex, $str, $matches)){ echo 'No i:Valid Successful!',"\n"; } if(preg_match($regex.'i', $str, $matches)){ echo 'YES i:Valid Successful!',"\n"; }
¤ 字符域:[\w]用方括號擴(kuò)起來的部分就是字符域。
¤ 限定符:如[\w]{3,5}或者[\w]*或者[\w]+這些[\w]后面的符號都表示限定符?,F(xiàn)介紹具體意義。
{3,5}表示3到5個字符。{3,}超過3個字符,{,5}最多5個,{3}三個字符。
* 表示0到多個
+ 表示1到多個。
¤ 脫字符號
^:
> 放在字符域(如:[^\w])中表示否定(不包括的意思)——“反向選擇”
> 放在表達(dá)式之前,表示以當(dāng)前這個字符開始。(/^n/i,表示以n開頭)。
注意,我們經(jīng)常管"\"叫"跳脫字符"。用于轉(zhuǎn)義一些特殊符號,如".","/"
通配符(lookarounds):斷言某些字符串中某些字符的存在與否!
lookarounds分兩種:lookaheads(正向預(yù)查 ?=)和lookbehinds(反向預(yù)查?<=)。
> 格式:
正向預(yù)查:(?=) 相對應(yīng)的 (?!)表示否定意思
反向預(yù)查:(?<=) 相對應(yīng)的 (?
前后緊跟字符
$regex = '/(?<=c)d(?=e)/'; /* d 前面緊跟c, d 后面緊跟e*/ $str = 'abcdefgk'; $matches = array(); if(preg_match($regex, $str, $matches)){ var_dump($matches); } echo "\n";
否定意義:
$regex = '/(?<!c)d(?!e)/'; /* d 前面不緊跟c, d 后面不緊跟e*/ $str = 'abcdefgk'; $matches = array(); if(preg_match($regex, $str, $matches)){ var_dump($matches); } echo "\n";
>字符寬度:零
驗(yàn)證零字符代碼
$regex = '/HE(?=L)LO/i'; $str = 'HELLO'; $matches = array(); if(preg_match($regex, $str, $matches)){ var_dump($matches); } echo "\n";
打印不出結(jié)果!
$regex = '/HE(?=L)LLO/i'; $str = 'HELLO'; $matches = array(); if(preg_match($regex, $str, $matches)){ var_dump($matches); } echo "\n";
能打印出結(jié)果!
說明:(?=L)意思是HE后面緊跟一個L字符。但是(?=L)本身不占字符,要與(L)區(qū)分,(L)本身占一個字符。
捕獲數(shù)據(jù)
沒有指明類型而進(jìn)行的分組,將會被獲取,供以后使用。
> 指明類型指的是通配符。所以只有圓括號起始位置沒有問號的才能被捕捉。
> 在同一個表達(dá)式內(nèi)的引用叫做反向引用。
> 調(diào)用格式: \編號(如\1)。
$regex = '/^(Chuanshanjia)[\w\s!]+\1$/'; $str = 'Chuanshanjia thank Chuanshanjia'; $matches = array(); if(preg_match($regex, $str, $matches)){ var_dump($matches); } echo "\n";
> 避免捕獲數(shù)據(jù)
格式:(?:pattern)
優(yōu)點(diǎn):將使有效反向引用數(shù)量保持在最小,代碼更加、清楚。
>命名捕獲組
格式:(?P<組名>) 調(diào)用方式 (?P=組名)
$regex = '/(?P<author>chuanshanjia)[\s]Is[\s](?P=author)/i'; $str = 'author:chuanshanjia Is chuanshanjia'; $matches = array(); if(preg_match($regex, $str, $matches)){ var_dump($matches); } echo "\n";
運(yùn)行結(jié)果
惰性匹配(記?。簳M(jìn)行兩部操作,請看下面的原理部分)
格式:限定符?
原理:"?":如果前面有限定符,會使用最小的數(shù)據(jù)。如“*”會取0個,而“+”會取1個,如過是{3,5}會取3個。
先看下面的兩個代碼:
代碼1.
<?php $regex = '/heL*/i'; $str = 'heLLLLLLLLLLLLLLLL'; if(preg_match($regex, $str, $matches)){ var_dump($matches); } echo "\n";
結(jié)果1.
代碼2
<?php $regex = '/heL*?/i'; $str = 'heLLLLLLLLLLLLLLLL'; if(preg_match($regex, $str, $matches)){ var_dump($matches); } echo "\n";
結(jié)果2
代碼3,使用“+”
<?php $regex = '/heL+?/i'; $str = 'heLLLLLLLLLLLLLLLL'; if(preg_match($regex, $str, $matches)){ var_dump($matches); } echo "\n";
結(jié)果3
代碼4,使用{3,5}
<?php $regex = '/heL{3,10}?/i'; $str = 'heLLLLLLLLLLLLLLLL'; if(preg_match($regex, $str, $matches)){ var_dump($matches); } echo "\n";
結(jié)果4
正則表達(dá)式的注釋
格式:(?# 注釋內(nèi)容)
用途:主要用于復(fù)雜的注釋
貢獻(xiàn)代碼:是一個用于連接MYSQL數(shù)據(jù)庫的正則表達(dá)式
$regex = '/ ^host=(?<!\.)([\d.]+)(?!\.) (?#主機(jī)地址) \| ([\w!@#$%^&*()_+\-]+) (?#用戶名) \| ([\w!@#$%^&*()_+\-]+) (?#密碼) (?!\|)$/ix'; $str = 'host=192.168.10.221|root|123456'; $matches = array(); if(preg_match($regex, $str, $matches)){ var_dump($matches); } echo "\n";
特殊字符
特殊字符 | 解釋 |
* | 0到多次 |
+ | 1到多次還可以寫成{1,} |
? | 0或1次 |
. | 匹配除換行符外的所有單個的字符 |
\w | [a-zA-Z0-9_] |
\s | 空白字符(空格,換行符,回車符)[\t\n\r] |
\d | [0-9] |
以上所述是小編給大家介紹的PHP正則表達(dá)式入門教程的相關(guān)知識,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對幫客之家網(wǎng)站的支持!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas
