Techno World Inc - The Best Technical Encyclopedia Online!

THE TECHNO CLUB [ TECHNOWORLDINC.COM ] => HTML => Topic started by: Daniel Franklin on September 26, 2007, 04:07:24 PM



Title: Parse html with preg_match_all
Post by: Daniel Franklin on September 26, 2007, 04:07:24 PM
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 webpage:

<?php
$data = file_get_contents("http://www.finalwebsites.com");
$pattern = "/src=["']?([^"']?.*(png|jpg|gif))["']?/i";
preg_match_all($pattern, $data, $images);
?>

We take a closer look to the pattern:
"/src=["']?([^"']?.*(png|jpg|gif))["']?/i"
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:
"/src=["']?([^"']?.*(png|jpg|gif))["']?/i"
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:
"/src=["']?([^"']?.*(png|jpg|gif))["']?/i"


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] -> scr="/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.

Articles Source - Free Articles