PHP中Regex函數

來源:互聯網
上載者:User
在PHP中有兩套Regex函數庫。一套是由PCRE(Perl Compatible Regular Expression)庫提供的,基於傳統型NFA。PCRE庫使用和Perl相同的文法規則實現了Regex的模式比對,其使用以“preg_”為首碼命名的函數。另一套是由POSIX(Portable Operation System interface)擴充庫提供的,基於POSIX NFA。POSIX擴充的Regex由POSIX 1003.2定義,一般使用以“ereg_”為首碼命名的函數。

兩套函數庫的功能相似,執行效率稍有不同。一般而言,實現相同的功能,使用PCRE庫的效率略佔優勢。下面詳細介紹其使用方法。

Regex的匹配

  1.preg_match()

    函數原型:int preg_match (string pattern,stringpattern,stringcontent [, array $matches])

    preg_match ()函數在content字串中搜尋與content字串中搜尋與pattern給出的Regex相匹配的內容。如果提供了matches,則將匹配結果放入其中。matches,則將匹配結果放入其中。matches[0]將包含與整個模式比對的文本,$matches[1]將包含第一個捕獲的與括弧中的模式單元所匹配的內容,以此類推。該函數只 作一次匹配,最終返回0或1的匹配結果數。

  2.ereg()和eregi()

    ereg()是POSIX擴充庫中Regex的匹配函數。eregi()是ereg()函數的忽略大小寫版 本。二者與preg_match的功能類似,但函數返回的是一個布爾值,表明匹配成功與否。需要說明的是,POSIX擴充庫函數的第一個參數接受的是正則 運算式字串,即不需要使用分界符。

3.preg_grep()

  函數原型:array preg_grep (string pattern,arraypattern,arrayinput)

  preg_grep()函數返回一個數組,其中包括了input數組中與給定的input數組中與給定的pattern模式相匹配的單元。對於輸入數組$input中的每個元素,preg_grep()也只進行一次匹配。代碼6.3給出的樣本簡單地說明了preg_grep()函數的使用。

進行全域Regex匹配

  1.preg_match_all()

  與preg_match()函數類似。如果使用了第三個參數,將把所有可能的匹配結果放入。本函數返回整個模 式匹配的次數(可能為0),如果出錯返回False。   

  2.多行匹配

  僅僅使用POSIX下的正則表式函數,很難進行複雜的匹配操作。例如,對整個檔案(尤其是多行文本)進行匹配尋找。使用ereg()對此進行操作的一個方法是分行處理。

Regex的替換

  1.ereg_replace()和eregi_replace()  

  函數原型:string ereg_replace (string pattern,stringpattern,stringreplacement, string $string)

string eregi_replace (string pattern,stringpattern,stringreplacement, string $string)

  ereg_replace()在string中搜尋模式字串string中搜尋模式字串pattern,並將所匹配結果替換 為replacement。當replacement。當pattern中包含模式單元(或子模式)時,replacement中形如“\1”或“replacement中形如“\1”或“1”的位置將依次被這些子 模式所匹配的內容替換。而“\0”或“$0”是指整個的匹配字串的內容。需要注意的是,在雙引號中反斜線作為轉義符使用,所以必須使用“\\0”,“ \\1”的形式。

eregi_replace()和ereg_replace()的功能一致,只是前者忽略大小寫。

  2.preg_replace()

  函數原型:mixed preg_replace (mixed pattern,mixedpattern,mixedreplacement, mixed subject[,intsubject[,intlimit])

  preg_replace較ereg_replace的功能更加強大。其前三個參數均可以使用數組;第四個參數$limit可以設定替換的次數,預設為全部替換。

Regex的拆分

  1.split()和spliti()

  函數原型:array split (string pattern,stringpattern,stringstring [, int $limit])

  本函數返回一個字串數組,每個單元為string經Regexstring經Regexpattern作為邊界分割出的子串。如 果設定了limit,則返回的數組最多包含limit,則返回的數組最多包含limit個單元。而其中最後一個單元包含了$string中剩餘的所有部分。spliti是split的 忽略大小版本。

  2.preg_split()

  本函數與split函數功能一致。'

相關推薦:

PHP中常用Regex函數詳解

linux系統使用者管理與grepRegex詳解

PHPRegex分享

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.