PHP preg functions - examples and comparision
Archive - Originally posted on "The Horse's Mouth" - 2009-07-08 23:04:14 - Graham Ellispreg_match('%CheckUpdateTime(.*?)Main content end%s',$stuff,$gotten);
preg_match_all('%(<td class="destination">.*?)</tr>%s',$gotten[1],$service);
foreach ($service[1] as $train) {
$teapot = preg_split('%</td>%',$train);
foreach ($teapot as $element) {
$el = preg_replace('%\s+%',' ',trim(strip_tags($element)));
print "$el\n";
}
print "-----------\n";
}
For this week's course, I have been doing some quite complex data extraction in PHP ... and the example code above uses a number of the major PHP regular expression functions,
Firstly, PHP has an "ereg" family using POSIX regular expressions, and a "preg" family using Perl style. I have used the latter - a little harder to understand at first, but more powerful and stated to be quicker. You may as well take the bull by the horns if you're jumping in!
preg_match creates an array - the whole matched string in the first element, and parts that match bracketed sections of the regular expression in the second (number 1!) and subsequent elements.
preg_match_all works like preg_match but creates a whole array for each element. Slightly surprisingly, the first array within the array is all the full strings, the second array is all the fist matches, etc.
The return values from preg_match and preg_match_all are simply reports of success and not the matched parts, which are in the named array passed in as the third parameter.
preg_split throws away each occurrence of a matching string and returns, as an array, the unmatching string sections in between
preg_replace takes an incoming string and replaces all matches to a particular pattern with an alternative string.
See full source of the example above, which pulls back data from Transport for London and tells you about the next departures from your local tube station!