PHP 的正则相关函数总结

正则程序员基本都会用到,但是用的都不多,本文总结、比较 PHP 常用的正则函数:

1. preg_match 和 preg_match_all

preg_match 与 preg_match_all 都是用来匹配正则表达式。

主要参数有三个:preg_match_all ( string patt,string str , array $matches);

$patt: 正则表达式。

$str: 匹配的字符串。

matches: matches)。

区别: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)

可选参数: flags offset 字符串偏移量。

2.preg_replace , preg_replace_callback和 preg_filter

这几个函数都是利用正则替换字符串的。原理都是先用正则匹配字符串,然后将匹配到的结果替换成目标字符串,返回替换后的字符串。

preg_replace ( patt, replacement , $str );

$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 )

$pattern : 正则表达式。

$str : 原字符串。

$limit : 最大保留截断数。(可选)

$flags: 返回集合(可选)

例:

$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
print_r($keywords);

输出:

Array
(
    [0] => hypertext
    [1] => language
    [2] => programming
)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值