使用preg_match和preg_match_all的区别

preg_match只匹配一次

preg_match_all是全文匹配,即所有跟表达式一致的都找出来。  


例如:

1.匹配字符串在规则中的所有字符:

2
preg_match_all( "/(\w)+/" , "abc" , $abc );
print_r( $abc );

显示的结果为:

1
2
3
4
Array( 
      [0] = Array ( [0] = a [1] = b [2] = c )  
      [1] = Array ( [0] = a [1] = b [2] = c ) 
)


2、匹配字符串在正则里的字符串,仅一次

1
2
preg_match( "/(\w)+/" , "abc" , $abc );
print_r( $abc ); 

 

显示结果  

1
2
3
Array( [0] = a 
[1] = 
a) 

这两个函数的区别是:

preg_match_all()搜索匹配全部情况;

preg_match()搜索匹配到一个后终止。


preg_match() 返回 pattern 所匹配的次数。

要么是 0 次(没有匹配)或 1 次,因为 preg_match() 在第一次匹配之后将停止搜索。


preg_match_all() 则相反,会一直搜索到 subject 的结尾处。

如果出错 preg_match() 返回 FALSE。 


猜你喜欢

转载自blog.csdn.net/wjn2000414/article/details/80369333