php之正規表示式函式總結

在荊棘路上的猴子發表於2019-02-16

php之正規表示式函式總結

  • 匹配

    用於匹配常用的函式有兩個,分別是preg_matchpreg_match_all

看程式碼:

//preg_match($pattern, $subject, &$match, [$flags=0], [$offset=0]) 一般三個引數

$pattern = `/[0-9]/`;  //正則
$subject = `abc1def2ghi3klm4`;    //需要匹配的字串
$return = preg_match($pattern, $subject, $matches);
echo $return; //1  因為匹配到了1個就會停止匹配
print_r($matches); // [`1`]  將所有滿足正則規則的匹配放到陣列裡。


//preg_match_all($pattern, $subject, $matches,...)
$pattern = `/[0-9]/`;//正則字串
$subject = `abc1def2ghi3klm4`;//需要匹配的目標字串
$return = preg_match_all($pattern, $subject, $matches);
echo $return;//4    因為會匹配所有的
print_r($matches);//[0=>[`1`,`2`,`3`,`4`]] 注意是個二維陣列。
  • 替換

    用於替換常用的函式也有兩個preg_replacepreg_filter,這兩個灰常的相似!!!

看程式碼:

//preg_replace($pattern, $replacement, $subject)

$pattern = `/[0-9]/`;
$replacement = `嘿嘿嘿`;
$subject = `a1b2c3`;
$return = preg_replace($pattern, $replacement, $subject);
echo $return; //`a嘿嘿嘿b嘿嘿嘿c嘿嘿嘿`


//preg_filter($pattern, $replacement, $subject)     //和preg_replace 沒有任何變化
$pattern = `/[0-9]/`;
$replacement = `嘿嘿嘿`;
$subject = `a1b2c3`;
$return = preg_filter($pattern, $replacement, $subject);
echo $return; //`a嘿嘿嘿b嘿嘿嘿c嘿嘿嘿`

//但是$pattern 和 $subject都是陣列呢
$pattern = array(`/[0-3]/`, `/[4-6]/`, `/[7-9]/`);
$replacement = array(`小`, `中`, `大`);
$subject = array(`a`, `b`, `1as`, `d`, `s5d`, `7qq`);
$return = preg_replace($pattern, $replacement, $subject);
print_r($return);
//結果
Array
(
    [0] => a
    [1] => b
    [2] => 小as
    [3] => d
    [4] => s中d
    [5] => 大qq
) 


$pattern = array(`/[0-3]/`, `/[4-6]/`, `/[7-9]/`);
$replacement = array(`小`, `中`, `大`);
$subject = array(`a`, `b`, `1as`, `d`, `s5d`, `7qq`);
$return = preg_filter($pattern, $replacement, $subject);
print_r($return);
//結果
Array
(
    [2] => 小as
    [4] => s中d
    [5] => 大qq
)
  • 陣列匹配 + 分割

    分別是preg_greppreg_split

看程式碼:

//趁熱打鐵  其實preg_grep呢 就是preg_filter的閹割版  只匹配  不替換而已
//preg_grep($pattern, $subject)
$subject = [`r`, `a2`, `b3`, `c`, `d`];
$pattern = `/[0-9]/`;
$fl_array = preg_grep($pattern, $subject);
print_r($fl_array);
//結果:
Array
(
    [1] => a2
    [2] => b3
)    //注意索引


//preg_split($pattern, $subject) 返回分割後的陣列
$subject = `a132b456c777d`;
$pattern = `/[0-9]+/`;   匹配至少一個數字
$return = preg_split($pattern, $subject);
print_r($return);
//結果:
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)

相關文章