PHP Regex匹配函數 preg_match 與 preg_match_all

來源:互聯網
上載者:User

標籤:

preg_match()

preg_match() 函數用於進行Regex匹配,成功返回 1 ,否則返回 0 。

文法:

int preg_match( string pattern, string subject [, array matches ] )

參數說明:

參數 說明
pattern Regex
subject 需要匹配檢索的對象
matches 可選,儲存匹配結果的數組, $matches[0] 將包含與整個模式比對的文本,$matches[1] 將包含與第一個捕獲的括弧中的子模式所匹配的文本,以此類推

例子 1:

<?phpif (preg_match("/php/i", "PHP is the web scripting language of choice.", $matches)){print "A match was found:" . $matches[0];}else{print "A match was not found.";}

輸出:

A match was found:PHP

在該例子中,由於使用了 i 修正符,因此會不區分大小寫去文本中匹配 php 。

 

注意:

preg_match() 第一次匹配成功後就會停止匹配,如果要實現全部結果的匹配,即搜尋到subject結尾處,則需使用 preg_match_all() 函數。

例子 2 ,從一個 URL 中取得主機網域名稱 :

<?php// 從 URL 中取得主機名稱preg_match("/^(http:\/\/)?([^\/]+)/i","http://blog.snsgou.com/index.php", $matches);$host = $matches[2];// 從主機名稱中取得後面兩段preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);echo "網域名稱為:{$matches[0]}";

輸出:

網域名稱為:snsgou.com

 

preg_match_all()

preg_match_all() 函數用於進行Regex全域匹配,成功返回整個模式比對的次數(可能為零),如果出錯返回 FALSE 。

文法:

int preg_match_all( string pattern, string subject, array matches [, int flags ] ) 

參數說明:

參數 說明
pattern Regex
subject 需要匹配檢索的對象
matches 儲存匹配結果的數組
flags

可選,指定匹配結果放入 matches 中的順序,可供選擇的標記有:

  1. PREG_PATTERN_ORDER:預設,對結果排序使 $matches[0] 為全部模式比對的數組,$matches[1] 為第一個括弧中的子模式所匹配的字串組成的數組,以此類推
  2. PREG_SET_ORDER:對結果排序使 $matches[0] 為第一組匹配項的數組,$matches[1] 為第二組匹配項的數組,以此類推
  3. PREG_OFFSET_CAPTURE:如果設定本標記,對每個出現的匹配結果也同時返回其附屬的字串位移量

下面的例子示範了將文本中所有 <pre></pre> 標籤內的關鍵字(php)顯示為紅色。

<?php$str = "<pre>學習php是一件快樂的事。</pre><pre>所有的phper需要共同努力!</pre>";$kw = "php";preg_match_all(‘/<pre>([\s\S]*?)<\/pre>/‘, $str, $mat);for ($i = 0; $i < count($mat[0]); $i++){$mat[0][$i] = $mat[1][$i];$mat[0][$i] = str_replace($kw, ‘<span style="color:#ff0000">‘ . $kw . ‘</span>‘, $mat[0][$i]);$str = str_replace($mat[1][$i], $mat[0][$i], $str);}echo $str;?>

輸出效果:

簡化一下:

<?php$str = "<pre>學習php是一件快樂的事。</pre><pre>所有的phper需要共同努力!</pre>";preg_match_all(‘/<pre>([\s\S]*?)<\/pre>/‘, $str, $matches);print_r($matches);?>

輸出:

Array(    [0] => Array        (            [0] => <pre>學習php是一件快樂的事。</pre>            [1] => <pre>所有的phper需要共同努力!</pre>        )    [1] => Array        (            [0] => 學習php是一件快樂的事。            [1] => 所有的phper需要共同努力!        ))

 

 

參考:

http://php.net/manual/zh/function.preg-match-all.php

PHP Regex匹配函數 preg_match 與 preg_match_all

聯繫我們

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