1. 正則表達式是一種字符串搜索和匹配的工具
2. php中常用正則表達式函數
3. 函數說明
$pattern = 正則表達式
$subject = 匹配的目標函數
(1) preg_match() 和 preg_match_all() : return 匹配到結果的次數
eg:
$pattern='/[0-9]/';
$subject = 'weuyr3ui76as83s0ck9';
$m1 = $m2 = array();
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 : 支持數組替換
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]=>啊!)