PHP Regex常用函數_php執行個體

來源:互聯網
上載者:User

1.preg_match()

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

<?php //需要匹配的字串。date函數返回目前時間 $content = "Current date and time is ".date("Y-m-d h:i a").", we are learning PHP together."; //使用通常的方法匹配時間 if (preg_match ("//d{4}-/d{2}-/d{2} /d{2}:/d{2} [ap]m/", $content, $m)) { echo "匹配的時間是:" .$m[0]. "/n"; } //由於時間的模式明顯,也可以簡單的匹配 if (preg_match ("/([/d-]{10}) ([/d:]{5} [ap]m)/", $content, $m)) { echo "當前日期是:" .$m[1]. "/n"; echo "目前時間是:" .$m[2]. "/n"; } ?>

這是一個簡單動態文本串匹配執行個體。假設當前系統時間是“2006年8月17日13點25分”,將輸出如下的內容。
匹配的時間是:2006-08-17 01:25 pm
當前日期是:2006-08-17
目前時間是:01:25 pm

2.ereg()和eregi()

ereg()是POSIX擴充庫中Regex的匹配函數。eregi()是ereg()函數的忽略大小寫版 本。二者與preg_match的功能類似,但函數返回的是一個布爾值,表明匹配成功與否。需要說明的是,POSIX擴充庫函數的第一個參數接受的是正則 運算式字串,即不需要使用分界符。例如,代碼6.2是一個關於檔案名稱安全檢驗的方法。
代碼6.2 檔案名稱的安全檢驗
代碼如下:

<?php $username = $_SERVER['REMOTE_USER']; $filename = $_GET['file']; //對檔案名稱進行過濾,以保證系統安全 if (!ereg('^[^./][^/]*$', $userfile)) { die('這不是一個非法的檔案名稱!'); } //對使用者名稱進行過濾 if (!ereg('^[^./][^/]*$', $username)) { die('這不是一個無效的使用者名稱'); } //通過安全過濾,拼合檔案路徑 $thefile = "/home/$username/$filename"; ?>

通常情況下,使用與Perl相容的Regex匹配函數perg_match(),將比使用ereg()或eregi()的速度更快。如果只是尋找一個字串中是否包含某個子字串,建議使用strstr()或strpos()函數。

Regex的替換

1.ereg_replace()和eregi_replace()

函數原型:string ereg_replace (string $pattern, string $replacement, string $string)
string eregi_replace (string $pattern, string $replacement, string $string)
ereg_replace()在$string中搜尋模式字串$pattern,並將所匹配結果替換 為$replacement。當$pattern中包含模式單元(或子模式)時,$replacement中形如“/1”或“$1”的位置將依次被這些子 模式所匹配的內容替換。而“/0”或“$0”是指整個的匹配字串的內容。需要注意的是,在雙引號中反斜線作為轉義符使用,所以必須使用“//0”,“ //1”的形式。
eregi_replace()和ereg_replace()的功能一致,只是前者忽略大小寫。代碼6.6是本函數的應用執行個體,這段代碼示範了如何對程式原始碼做簡單的清理工作。
代碼6.6 原始碼的清理
代碼如下:

<?php $lines = file('source.php'); //將檔案讀入數組中 for($i=0; $i<count($lines); $i++) { //將行末以“//”或“#”開頭的注釋去掉 $lines[$i] = eregi_replace("(////|#).*$", "", $lines[$i]); //將行末的空白消除 $lines[$i] = eregi_replace("[ /n/r/t/v/f]*$", "/r/n", $lines[$i]); } //整理後輸出到頁面 echo htmlspecialchars(join("",$lines)); ?>

2.preg_replace()

函數原型:mixed preg_replace (mixed $pattern, mixed $replacement, mixed $subject [, int $limit])
preg_replace較ereg_replace的功能更加強大。其前三個參數均可以使用數組;第四個參數$limit可以設定替換的次數,預設為全部替換。代碼6.7是一個數組替換的應用執行個體。
代碼6.7 數組替換
代碼如下:

<?php //字串 $string = "Name: {Name}<br>/nEmail: {Email}<br>/nAddress: {Address}<br>/n"; //模式 $patterns =array( "/{Address}/", "/{Name}/", "/{Email}/" ); //替換字串 $replacements = array ( "No.5, Wilson St., New York, U.S.A", "Thomas Ching", "tom@emailaddress.com", ); //輸出模式替換結果 print preg_replace($patterns, $replacements, $string); ?>

輸出結果如下。

Name: Thomas Ching", Email: tom@emailaddress.com Address: No.5, Wilson St., New York, U.S.A 

在preg_replace的Regex中可以使用模式修正符“e”。其作用是將匹配結果用作運算式,並且可以進行重新運算。例如:
代碼如下:

<?php $html_body = “<HTML><Body><H1>TEST</H1>My Picture<Img src=”my.gif”></Body></HTML>”; //輸出結果中HTML標籤將全部為小寫字母 echo preg_replace ( "/(<//?)(/w+)([^>]*>)/e", "'//1'.strtolower('//2').'//3'", //此處的模式變數//2將被strtolower轉換為小寫字元 $html_body); ?>

提示
preg_replace函數使用了Perl相容Regex文法,通常是比ereg_replace更快的替代方案。如果僅對字串做簡單的替換,可以使用str_replace函數。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.