PHP preg_matchRegex的使用_PHP教程

來源:互聯網
上載者:User
在php中preg_match()函數是用來執行Regex的一個常用的函數,下面我來給大家詳細介紹preg_match使用方法。

函數用法

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

例1

代碼如下 複製代碼

preg_match_all ("|<[^>]+>(.*)]+>|U","example:

this is a test",$out, PREG_SET_ORDER);
print $out[0][0].", ".$out[0][1]."n";
print $out[1][0].", ".$out[1][1]."n";
?>

本例將輸出:
example: , example:

this is a test, this is a test

例2

URL 中取出網域名稱

代碼如下 複製代碼

// 從 URL 中取得主機名稱
preg_match("/^(http://)?([^/]+)/i", "http://www.***.net/index.html", $matches);
$host = $matches[2];
// 從主機名稱中取得後面兩段
preg_match("/[^./]+.[^./]+$/", $host, $matches);
echo "domain name is: {$matches[0]}n";
?>

本例將輸出:

domain name is: PPP.NET

preg_match字串長度問題

preg_match正則提取目標內容,死活有問題,代碼測得死去活來。

後來懷疑PHP 的preg_match有字串長度限制,果然,發現“pcre.backtrack_limit ”的值預設只設了100000。

解決辦法:

代碼如下 複製代碼
ini_set('pcre.backtrack_limit', 999999999);

註:這個參數在php 5.2.0版本之後可用。

另外說說關於:pcre.recursion_limit

pcre.recursion_limit是PCRE的遞迴限制,這個項如果設很大的值,會消耗所有進程的可用堆棧,最後導致PHP崩潰。

也可以通過修改配置來限制:

代碼如下 複製代碼
ini_set('pcre.recursion_limit', 99999);

實際項目應用中,最好也對記憶體進行限定設定:ini_set('memory_limit', '64M'); , 這樣就比較穩妥妥嘎。


http://www.bkjia.com/PHPjc/445283.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/445283.htmlTechArticle在php中preg_match()函數是用來執行Regex的一個常用的函數,下面我來給大家詳細介紹preg_match使用方法。 函數用法 int preg_match_all ( stri...

  • 聯繫我們

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