首页 > Web开发 > 详细

PHP正则表达式常用函数

时间:2019-11-01 14:03:29      阅读:82      评论:0      收藏:0      [点我收藏+]

以下部分例子引用自手册 详情请查看手册 此处只是个人归纳
1.preg_grep()

函数语法:array preg_grep(string pattern, array input)
函数功能:使用input中的元素匹配表达式pattern,返回匹配的元素数组。
例子 :
<?php $pattern = ‘/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/‘; $input = array(‘test-001@qq.com‘,‘test2@163.net‘,‘123454test‘); $ret = preg_grep($pattern, $input); var_dump($ret); ?>
结果:array(2) { [0]=> string(15) "test-001@qq.com" [1]=> string(13) "test2@163.net" }

2.preg_match()/preg_match_all()

函数语法:int preg_match/preg_match_all(string pattern, string subject[,array matches])
函数功能:在subject中匹配pattern,返回匹配的次数。如果matches存在,则匹配的结果将被存储到matches中
区别:前者第一次匹配后就停止搜索,后者则会一直搜索到subject结尾
PHP <?php $pattern = ‘/\b\w{2}\b/‘; $input = ‘This is an example‘; $ret1 = preg_match($pattern, $input, $arr1); $ret2 = preg_match_all($pattern, $input,$arr2); var_dump($ret1); var_dump($ret2); ?>
结果: array(1) { [0]=> string(2) "is" } array(1) { [0]=> array(2) { [0]=> string(2) "is" [1]=> string(2) "an" } }

3.preg_quote()

函数语法:string preg_quote( string $str[, string $delimiter = NULL] )
函数功能:对str的特殊字符转义,返回转义后的字符串
正则表达式特殊字符有: . ?+ * ? [ ^ ] $ ( ) { } = ! < > | : -
php <?php $keywords = ‘$40 for a g3/400‘; $keywords = preg_quote($keywords, ‘/‘); echo $keywords; // 返回 \$40 for a g3\/400 ?>
4.preg_replace()
函数语法:mixed preg_replace( mixed $pattern, mixed $replacement, mixed $subject[, int $limit = -1[, int &$count]] )
函数功能:搜索subject中匹配pattern的部分,以replacement进行替换。
5.preg_replace_callback()
函数语法:mixed preg_replace_callback( mixed $pattern, callable $callback, mixed $subject[, int $limit = -1[, int &$count]] )
函数功能:执行一个正则表达式搜索并且使用一个回调进行替换
php $str = "I like php\n"; $str .= "I like php too\n"; function callback(){ return ‘python‘; } echo preg_replace_callback(‘/php/‘, ‘callback‘, $str);
结果: I like python I like python too
6.preg_split()
函数语法:
array preg_split( string $pattern, string $subject[, int $limit = -1[, int $flags = 0]] )**
函数功能:通过一个正则表达式分隔字符串
php //使用空格逗号分隔字符串 $str = "I like,php"; var_dump(preg_split(‘/\s+/‘, $str));
结果: array(3) { [0]=> string(1) "I" [1]=> string(4) "like" [2]=> string(3) "php" }

PHP正则表达式常用函数

原文:https://www.cnblogs.com/sthzx/p/11776544.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!