浅谈preg_match与preg_match_all区别

来源:互联网 发布:js 绑定点击事件 编辑:程序博客网 时间:2024/05/16 10:39
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个(),如此类推。因为第一个()就是匹配所有的内容。哪么它们当然是一样了。

0 0
原创粉丝点击