正則程序員基本都會用到,但是用的都不多,本文總結、比較 PHP 常用的正則函數:
1. preg_match 和 preg_match_all
preg_match 與 preg_match_all 都是用來匹配正則表達式。
主要參數有三個:preg_match_all ( string
$patt: 正則表達式。
$str: 匹配的字符串。
區別:preg_match_all 輸出所有匹配結果。 preg_match 默認輸出第一個匹配結果。
例如:
$str = 'hi,this is his history';
$patt = '/\bhi/';
preg_match_all($patt,$str,$matches);
var_dump($matches);
preg_match($patt,$str,$matches);
var_dump($matches);
輸出結果:
array (size=1)
0 =>
array (size=3)
0 => string 'hi' (length=2)
1 => string 'hi' (length=2)
2 => string 'hi' (length=2)
array (size=1)
0 => string 'hi' (length=2)
可選參數:
2.preg_replace , preg_replace_callback和 preg_filter
這幾個函數都是利用正則替換字符串的。原理都是先用正則匹配字符串,然後將匹配到的結果替換成目標字符串,返回替換後的字符串。
preg_replace (
$patt: 匹配正則表達式。
$replacement:要替換成的目標字符。
$str: 原始字符串。
例如:
$str = 'hi,this is his history';
$patt = '/\bhi/';
$str = preg_replace($patt,'hollow',$str);
echo $str;
輸出:
hollow,this is hollows hollowstory
preg_replace_callback 即是將第二個參數換成一個方法。
例如:
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
function next_year($matches)
{
return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
"|(\d{2}/\d{2}/)(\d{4})|",
"next_year",
$text);
preg_filter 的用法與preg_replace相同。
3. preg_grep
正則匹配一組數組,返回數據中符合正則的元素數組。
$arr = ['hi','hollow','show'];
$patt = '/ho/';
$z = preg_grep($patt,$arr);
print_r($z);
返回:
Array ( [1] => hollow [2] => show )
4.preg_split 分割字符串
通過一個正則表達式分隔給定字符串.
preg_splite(
$pattern : 正則表達式。
$str : 原字符串。
$limit : 最大保留截斷數。(可選)
$flags: 返回集合(可選)
例:
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
print_r($keywords);
輸出:
Array
(
[0] => hypertext
[1] => language
[2] => programming
)