1. Home
  2. Computing & Technology
  3. PHP / MySQL

Introduction to Preg in PHP

By Angela Bradley, About.com

3 of 5

Preg_Match_All PHP Function

Preg_Match_All is used to search a string for specific patterns and stores the results in an array. Unlike preg_match which stops searching after it finds a match, preg_match_all searches the entire string and records all matches. It is phrased as: preg_match_all (pattern, string, $array, optional_ordering, optional_offset)

<? $data = "The party will start at 10:30 pm and run untill 12:30 am";
preg_match_all('/(\d+:\d+)\s*(am|pm)/', $data, $match, PREG_PATTERN_ORDER);
echo "Full: <br>";
print_r($match[0]);
echo "<p>Raw: <br>";
print_r($match[1]);
echo "<p>Tags: <br>";
print_r($match[2]);
?>
In our first example we use PREG_PATTERN_ORDER. We are searching for 2 things; one is the time, the other is it's am/pm tag. Our results are outputted to $match, as an array where $match[0] contains all matches, $match[1] contains all data matching our first sub-serach (the time) and $match[2] contains all data matching our second sub-search (am/pm).

<? $data = "The party will start at 10:30 pm and run untill 12:30 am";
preg_match_all('/(\d+:\d+)\s*(am|pm)/', $data, $match, PREG_SET_ORDER);
echo "First: <br>";
echo $match[0][0] . " , " . $match[0][1] . " , ". $match [0][2] ."<br>";
echo "Second: <br>";
echo $match[1][0] . " , " . $match[1][1] . " , ". $match [1][2] ."<br>";
?>
In our second example we use PREG_SET_ORDER. This puts each full result into an array. The first result is $match[0], with $match[0][0] being the full match, $match[0][1] being the first sub-match and $match[0][2] being the second sub-match.

3 of 5

Explore PHP / MySQL

More from About.com

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. PHP Functions
  5. Preg_Match_All - Preg Match All PHP - PHP Function Preg_Match_All

©2008 About.com, a part of The New York Times Company.

All rights reserved.