PHP常用Regex函數淺析

來源:互聯網
上載者:User

標籤:ar   sp   div   c   on   r   bs   python   as   

1. preg_match()函數
   preg_match()函數在字串中搜尋模式,如果存在則返回true,否則返回false
   
   $pattern=‘/php/‘;
   $str=‘php100.com‘;
   echo preg_match($pattern,$str);
   
   輸出結果:1

2. preg_grep()函數
   preg_grep()函數搜尋數組中的所有元素,返回由與某個模式比對的所有元素組成的數組
   
   $pattern=‘/p$/‘;
   $strArray=array(‘asp‘,‘php‘,‘jsp‘,‘python‘,‘ruby‘);
   print_r(preg_grep($pattern,$strArray));
   
   輸出結果:
       Array
   (
       [0] => asp
       [1] => php
       [2] => jsp
   )

3. preg_match_all()函數
   preg_match_all()函數在字串中匹配模式的所有出現,然後將所有匹配到的全部放入數組
   
   $pattern=‘/php[1-5]/‘;
   $str=‘php1php2php3php4php5php6php7php8‘;
   preg_match_all($pattern,$str,$out);
   print_r($out);
   
   輸出結果:
   Array
   (
       [0] => Array
           (
               [0] => php1
               [1] => php2
               [2] => php3
               [3] => php4
               [4] => php5
           )
   
   )

4. preg_quote()函數
   preg_quote()函數在每個對於Regex文法而言有特殊含義的字元前插入一個反斜線。
   
   echo preg_quote(‘蘋果的價格是:$5/千克‘);
   
   輸出結果:蘋果的價格是:\$5/千克    

5. preg_replace()函數
   preg_replace()函數搜尋到所有的匹配,然後替換成想要的字串返回
   
   $pattern=‘/php[1-5]/‘;
   $str=‘php1php2php3php4php5php6php7php8‘;
   
   echo preg_replace($pattern,‘PHP‘,$str);
   
   輸出結果:PHPPHPPHPPHPPHPphp6php7php8

6. preg_split()函數
   preg_split()函數以不區分大小寫方式分割字串,將所得到的字串組成數組並返回
   
   $pattern=‘/[\[email protected]]/‘;
   $str=‘[email protected]‘;
   
   print_r(preg_split($pattern,$str));
   
   輸出結果:
   Array
   (
       [0] => feng
       [1] => yingyuan
       [2] => sina
       [3] => com
       [4] => cn
   )

PHP常用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.