PHP 的正则相关函数总结
来源:互联网 发布:32位ubuntu镜像下载 编辑:程序博客网 时间:2024/05/16 16:03
正则程序员基本都会用到,但是用的都不多,本文总结、比较 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)
阅读全文
0 0
- PHP 的正则相关函数总结
- PHP正则相关的几个preg函数
- PHP中Perl兼容类型的正则表达式相关函数总结
- PHP的正则处理函数总结分析
- php正则表达式相关函数
- PHP、Python 相关正则函数一点实例
- php的相关函数
- php ping 的相关总结
- PHP的FTP相关函数
- 安全相关的PHP函数
- PHP数组相关的函数
- javaScript正则表达式相关函数的使用
- JS正则相关函数
- 总结php常用的正则表达式规范
- 关于PHP正则表达式的总结
- php preg_match正则函数的使用注意
- php----正则表达式所用到的函数
- (PHP)正则表达式-preg_split函数的用法
- 58. Length of Last Word
- 10. 电池曲线
- iOS 手势
- GO语言多值返回
- PagingAndSortingRepository
- PHP 的正则相关函数总结
- 最后的纪念——FromATP
- 冒泡
- 11. dws配置与调试
- Webdirver API (Python版)
- js网页添加水印
- android webview JS对话框 不能弹出 解决办法
- 关于见习的课后思考
- TabLayout设置字体为normal