PHP 正則表達式匹配函數 preg_match 與 preg_match_all

preg_match()php

preg_match() 函數用於進行正則表達式匹配,成功返回 1 ,不然返回 0 。web

語法:正則表達式

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

參數說明:數組

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

例子 1:函數

<?php
if (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 。spa

 

注意:.net

preg_match() 第一次匹配成功後就會中止匹配,若是要實現所有結果的匹配,即搜索到subject結尾處,則需使用 preg_match_all() 函數。對象

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

<?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() 函數用於進行正則表達式全局匹配,成功返回整個模式匹配的次數(可能爲零),若是出錯返回 FALSE 。

語法:

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

參數說明:

參數 說明
pattern 正則表達式
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

相關文章
相關標籤/搜索