PHPRegex匹配替換與分割功能執行個體

來源:互聯網
上載者:User
這篇文章主要介紹了PHPRegex匹配替換與分割功能,簡單分析了php正則匹配、替換與分割相關函數,並結合執行個體形式示範了php正則匹配的相關操作技巧,需要的朋友可以參考下

具體如下:

Regex在PHP中的作用主要包括:分割、匹配、尋找與替換。

匹配功能

preg_match_all 全部匹配函數

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

對結果的排序使 $matches[0] 為全部模式比對的數組。

用途:截取比較精確的內容,用於採集網頁,分析文本等。

替換功能

preg_replace 正則替換函數

preg_replace(mixed pattern,mixed replacement,mixed subject[, int limit]);

通過Regex來替換相關內容。

① 替換內容可以是一個正則也可以是數組;
② 替換內容可以通過修正符 e 來解決替換執行內容。

用途:替換一些比較複雜的內容,也可以將內容進行轉換。

分割功能

preg_split 正則切割

preg_split(string pattern,string subject[, int limit[, int flags]]);

通過Regex來切割相關內容,類似 explode 切割函數,但 explode 只能以一種方式進行切割。

執行個體示範

匹配功能

以下為引用內容:

<?php$str="標題:{title}內容:{content}";$mode="/{(.*)}/U";preg_match_all($mode,$str,$arr);print_r($arr);?>

輸出:(在源檔案中查看)

以下為引用內容:

Array(  [0] => Array    (      [0] => {title}      [1] => {content}    )  [1] => Array    (      [0] => title      [1] => content    ))

以上就是本文的全部內容,希望對大家的學習有所協助。


聯繫我們

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