regular expression (php函数),regularexpression
regular expression (php函数),regularexpression
1. 正则表达式是一种字符串搜索和匹配的工具
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. 函数说明
$pattern = 正则表达式
$subject = 匹配的目标函数
(1) preg_match() 和 preg_match_all() : return 匹配到结果的次数
- preg_match($pattern, $subject, [array &$matches]) : 只匹配一次, 结果为0或者1, 第三个参数可不写, 第三个参数表示地址的引用
- preg_match($pattern, $subject, array &$matches) : 匹配全部, 结果为0,1,2......
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 : 支持数组替换
- 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]=>啊!)
上一篇: php文本分页代码:php读取txt文本文件并分页显示
下一篇: PHP 二维数组的读出,该如何处理
推荐阅读
-
regular expression (php函数),regularexpression
-
regular expression (php函数),regularexpression_PHP教程
-
Regular expression to match PHP function names
-
regular expression (php函数),regularexpression
-
regular expression (php函数),regularexpression_PHP教程
-
regularexpression php正则表达式regar expression
-
php 正则表达式(Regular Expression)用法
-
regular expression (php函数) - yanying12138
-
php 正则表达式(Regular Expression)用法
-
regular expression (php函数) - yanying12138