1. 正则表达式是一种字符串搜索和匹配的工具
2. php中常用正则表达式函数
3. php函数说明
$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]=>啊!)
(5) grep_quote($str) : 正则运算符转义
eg:
$str = 'asgs{kkk}[123]' $str = grep_quote($str)
结果:
asgs\{kkk\}\[123\]