PHP preg_match_all() Function

PHP preg_match_all() Function


Hello folks! welcome back to a new section of our tutorial on PHP. In this tutorial guide, we are going to be studying about the PHP preg_match_all() Function.

PHP preg_match_all() function matches all the occurrences of pattern in a string.

This PHP function places these matches in the array pattern_array in the order that you specify using the optional input parameter order. There are two possible types of order and they are -

  • PREG_PATTERN_ORDER - This is the default if the optional order parameter is not added. PREG_PATTERN_ORDER specifies the order in a way you might think most logical; $pattern_array[0] is an array of complete pattern matches, $pattern_array[1] is an array of strings that matches the first parenthesized regexp.
  • PREG_SET_ORDER - This orders the array a bit differently than the default setting. $pattern_array[0] contains the elements that are matched by the first parathesized regexp, $pattern_array[1] contains elements that are matched by the next parenthesized regexp, etc.


Syntax

The following is the syntax to make use of the preg_match_all() function -

string preg_match_all (string pattern,  string string,  array pattern_array [,  int order] );

Return Value

  • This returns the numbers of matchings.

Example

Following is a simple example -

<?php
   $userinfo = "Name: <b>Bethel Prince</b> <br> Title: <b>PHP Guru</b>";
   preg_match_all ("/<b>(.*)<\/b>/U", $userinfo, $pat_array);
   
   print $pat_array[0][0]." <br> ".$pat_array[0][1]."\n";
?>

Output

When the above code is executed, it will produce the following result -

Bethel Prince 
PHP Guru


Alright guys! This is where we are rounding up for this tutorial post. In our next tutorial guide, we are going to be discussing about the PHP preg_replace() Function.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.