This article analyzes and introduces the preg_match function and preg_match_all function in PHP regular expressions. Friends in need can refer to it.
preg_match_all() function
Search in the given string according to the specified regular expression and match Take out the parts that fit the characteristics.
$pattern='/t(.*?)st/'; $str='tgvregbvst test tdst'; var_dump(preg_match_all($pattern,$str,$arr)); var_dump($arr);
We can see that the output result is:
int(3) array(2) { [0]=> array(3) { [0]=> string(10) "tgvregbvst" [1]=> string(4) "test" [2]=> string(4) "tdst" } [1]=> array(3) { [0]=> string(7) "gvregbv" [1]=> string(1) "e" [2]=> string(1) "d" } }
He lists all those that meet the conditions, but the preg_match() function is different.
preg_match() function
Performs a regular expression match and returns the number of pattern
matches. Its value will be 0 (no match) or 1 because preg_match()
will stop the search after the first match.
$pattern='/t(.*?)st/'; $str='tgvregbvst test tdst'; var_dump(preg_match($pattern,$str,$arr)); var_dump($arr);
We can see that the output result is:
int(1) array(2) { [0]=> string(10) "tgvregbvst" [1]=> string(7) "gvregbv" }
Compared with the previous function, the output result of this function is much less. This is their difference.
preg_match_all()
Unlike the preg_match()
function, it will search subject
until it reaches the end. If an error occurs preg_match()
returns false
.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of A brief discussion on the difference between preg_match and preg_match_all functions in PHP. For more information, please follow other related articles on the PHP Chinese website!