Parse html with PHP preg_match_all()


For the most of the PHP developer which are using preg_match or preg_replace frequently is the function preg_match_all a smaller advantage, but for all others it’s maybe hard to understand. The biggest difference between preg_match_all and the regular preg_match is that all matched values are stored inside a multi-dimensional array to store an unlimited number of matches. With the following example I will try to make clear how its possible to store the image paths inside a web page:

$data = file_get_contents("");
$pattern = "/src=[\"']?([^\"']?.*(png|jpg|gif))[\"']?/i";
preg_match_all($pattern, $data, $images);

We take a closer look to the pattern:


The first part and the last part are searching for everything that starts with src and ends with a optional quote or double quote. This could be a long string because the outer rule is very global. Next we check the rule starts within the first bracket:


Now we are looking inside this long string from the outer rule for strings starting with an optional quote or double quote followed by any characters. The last part inside the inner brackets is the magic:


We are looking next for a string that is followed by a file extension and match we get all the paths from the html file.

We need all the rules to isolate the string parts (image paths) from the rest of the html. The result looks like this (access the array $images with these indexes, or just use print_r($images)):

$images[0][0] -> src="/images/english.gif"

$images[1][0] -> /images/english.gif

$images[2][0] -> gif

The index 1 is the information we need, try this example with other part of html code for a better understanding.

Loading related posts...


Post a Comment

2010 WEBSITE20. All rights reserved.