浅谈preg_match与preg_match_all区别

本文深入解析PHP中的preg_match和preg_match_all函数的区别,通过实例展示如何使用正则表达式进行匹配,并详细说明两者在匹配过程中的不同之处。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

preg_match和preg_match_all都是用来匹配正则表达式,哪么两者之间有什么区别呢?preg_match ( string pattern, string subject [, array matches [, int flags]] ); string pattern

是用来书写正则表达式,string subject 是要匹配的内容,array matches 是匹配的结果。preg_match_all ( string pattern, string subject, array matches [, int flags] )进行全局正则表达式匹配,对结果排序使 $matches[0] 为全部模式匹配的数组,$matches[1] 为第一个括号中的子模式所匹配的字符串组成的数组,以此类推。

preg_match 只区配一个结果就结速返回,而preg_match_all则匹配所有的结果。如例:

<?php $mode = '/([0-9][a-z])/i'; $subject = '0hello worlde 2my you2'; if (preg_match($mode, $subject, $matches)) { print_r($matches); } preg_match_all($mode, $subject, $matches); print_r($matches);?>

结果:

Array
(
    [0] => 0h
)
Array
(
    [0] => Array
        (
            [0] => 0h
            [1] => 2m
        )

)


透过上面的结果 ,你会看见preg_match只匹配了一个结果,而preg_match_all却有两个匹配结果,这就他们的区别所在,'/[0-9]['a-z']/'是筛选出第一位是整数,第二位是字母,我们经过观察,很容易就会发现0h 与2m都是符合的,但,preg_match只匹配一个结果,遇到到0h就返回。如果正则表达式修改为: '/([0-9][a-z])/'再看打印结果:

Array
(
    [0] => 0h
    [1] => 0
)
Array
(
    [0] => Array
        (
            [0] => 0h
            [1] => 2m
        )

    [1] => Array
        (
            [0] => 0
            [1] => 2
        )

)
你会发现两个数组均多了一个子集,你会现0并不匹配上面正则表达,哪么它是区配什么的呢,其实他是匹配第一个() 的,也就是[0-9]哪么就匹配 0 ,2 了,当然它只能在$matches[0]所对应的内容下进行匹配。下面再修改正则: '/(([0-9][z-a]))/i';理所当然,$matches又会增加一个子集:

Array
(
    [0] => 0h
    [1] => 0h
    [2] => 0
)
Array
(
    [0] => Array
        (
            [0] => 0h
            [1] => 2m
        )

    [1] => Array
        (
            [0] => 0h
            [1] => 2m
        )

    [2] => Array
        (
            [0] => 0
            [1] => 2
        )

)

会发现:$matches[0]和$matces[1]是完全一样,1代表第一个(),2代表第2个(),如此类推。因为第一个()就是匹配所有的内容。哪么它们当然是一样了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值