regular expression (php函數)

1. 正則表達式是一種字符串搜索和匹配的工具php

2. php中經常使用正則表達式函數正則表達式

  • preg_match($pattern, $subject)
  • preg_match_all($pattern, $subject, array &$matches)
  • preg_replace($pattern, $replacement, $subject)
  • preg_filter($pattern, $replacement, $subject)
  • preg_grep($pattern, array $input)
  • preg_split($pattern, $subject)
  • preg_quote($str)

3. php函數說明數組

$pattern = 正則表達式函數

$subject = 匹配的目標函數工具

  (1) preg_match() 和 preg_match_all() : return 匹配到結果的次數ui

  • preg_match($pattern, $subject, [array &$matches]) : 只匹配一次, 結果爲0或者1, 第三個參數可不寫, 第三個參數表示地址的引用
  • preg_match($pattern, $subject, array &$matches) : 匹配所有, 結果爲0,1,2......

  eg:blog

    $pattern='/[0-9]/';three

    $subject = 'weuyr3ui76as83s0ck9';字符串

    $m1 = $m2 = array();input

    t1 = grep_match($pattern, $subject, $m1);

    t2 = grep_match_all($pattern, $subject, $m2);

  結果: m1 = array([0]=>3)

    m2 = array([0]=>array([0]=>3,[1]=>7,[2]=>6,[3]=>8,[4]=>3,[5]=>0,[6]=>9))

    t1 = 1

    t2 = 7

  (2) preg_replace 與 preg_filter : 支持數組替換

  • preg_replace($pattern, $replacement, $subject) : 保留髮生替換和沒發生替換的值
  • preg_filter($pattern, $replacement, $subject) : 保留髮生替換的值

  eg one:

    $pattern='/[0-9]/';

    $subject = 'weuyr3ui76as83s0ck9';

    $replacement = '盈';

    $str1 = preg_replace($pattern, $replacement, $subject);

    $str2 = preg_filter($pattern, $replacement, $subject);

  結果:

    $str1 = 'weuyr盈ui盈盈as盈盈s盈ck盈'

    $str2 = 'weuyr盈ui盈盈as盈盈s盈ck盈'

  eg two:

    $pattern = array('/[0123]/', '/[456]/', '/[789]/')

    $replacement = array('啊', '啦', '嗦')

  結果:

    $str1 = 'weuyr啊ui嗦啦as嗦啊s啊ck嗦'

    $str2 = 'weuyr啊ui嗦啦as嗦啊s啊ck嗦'

  eg three:

    $subject = array('weuy', 'r3ui', '76as83', 's', '0ck9');

  結果:

    $str1 = array([0]=>weuy, [1]=>r啊ui, [2]=>嗦啦as嗦啊, [3]=>s, [4]=>啊ck嗦)

    $str2 = array([1]=>r啊ui, [2]=>嗦啦as嗦啊, [4]=>啊ck嗦)

  (3) grep_grep($pattern, array $input) : 閹割版的grep_filter(), 只作匹配, 不作替換

  eg:

    $pattern='/[0-9]/';

    $subject = array('weuy', 'r3ui', '76as83', 's', '0ck9');

    $arr = preg_grep($pattern, $subject);

   結果:

    $arr = array([1]=>r3ui, [2]=>76as83, [4]=>0ck9)

  (4) grep_split($pattern, $subject) : explode是該函數的子集

  eg:

    $pattern = '/[0-9]/';

    $subject = '你2好3啊!'

    $arr = preg_split($pattern, $subject);

  結果:

    $arr = ([0]=>你, [1]=>好, [2]=>啊!)

  (5) grep_quote($str) : 正則運算符轉義

  eg:

        $str = 'asgs{kkk}[123]'
        $str = grep_quote($str)    

  結果:

    asgs\{kkk\}\[123\]

相關文章
相關標籤/搜索