分析PHP函數preg_match()的具體程式碼範例_PHP教程

來源:互聯網
上載者:User
PHP函數preg_match()原型:int preg_match (string $pattern, string $content [, array $matches])

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

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

這是一個簡單動態文本串匹配執行個體。假設當前系統時間是“2006年8月17日13點25分”,將輸出如下的內容。
匹配的時間是:2006-08-17 01:25 pm
當前日期是:2006-08-17
目前時間是:01:25 pm
以上就是PHP函數preg_match()的具體功能樣本,希望大家能夠掌握。


http://www.bkjia.com/PHPjc/446252.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/446252.htmlTechArticlePHP函數preg_match()原型:int preg_match (string $pattern, string $content [, array $matches]) PHP函數preg_match()在$content字串中搜尋與$pattern給出的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.