PHP總結Regex相關函數用法

來源:互聯網
上載者:User

今天深入的把Regex看了一下,總結一下php的Regex所使用的函數

preg_match();
preg_match_all();
preg_replace();
preg_filter();
preg_grep();
preg_split();
preg_quote();

基本有這麼多吧。

一個個來

先給大家介紹一個 線上 驗證 Regex的工具

http://regexpal.isbadguy.com/

開啟你就明白怎嗎用了,我們先來說

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

這個很簡單直接來個例子就明白了

$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
preg_match_all() 函數用於進行Regex全域匹配,成功返回整個模式比對的次數(可能為零),如果出錯返回 FALSE 。

preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
    "<b>example: </b><div align=left>this is a test</div>",
    $out, PREG_PATTERN_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";

我們來重點講講

preg_replace();

preg_filter();

這兩個函數的區別

$subject = array('1', 'a', '2', 'b', '3', 'A', 'B', '4');
$pattern = array('/d/', '/[a-z]/', '/[1a]/');
$replace = array('A:$0', 'B:$0', 'C:$0');
echo "preg_filter returns ";
print_r(preg_filter($pattern, $replace, $subject));
echo "preg_replace returns ";
print_r(preg_replace($pattern, $replace, $subject));

很明顯我們可以看一下結果

preg_filter returns Array
(
    [0] => C:1
    [1] => B:C:a
    [3] => B:b
)
preg_replace returns Array
(
    [0] => C:1
    [1] => B:C:a
    [2] => 2
    [3] => B:b
    [4] => 3
    [5] => A
    [6] => B
    [7] => 4
)
這樣就很明顯了,preg_filter不會保留不匹配的選項,而preg_replace會保留不匹配的選項

preg_grep — 返回匹配模式的數組條目

$array = array("23.32","22","12.009","23.43.43");
print_r(preg_grep("/^(\d+)?\.\d+\.\d+$/",$array));

preg_split — 通過一個Regex分隔字串

這個函數要提得一點是,explode()可以算是這個函數的一個子集

preg_quote — 轉義Regex字元

最後這個函數就沒什麼好講的了。就是不讓執行Regex,轉義一下字元,和自己手動加\轉移是一樣的

聯繫我們

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