hrefextractor.phps

<?php
 
// regular expression <\s*a\s+[^>]*href\s*=\s*[\"']?([^\"' >]+)[\"' >]
 
$href_regex ="<";            // 1 start of the tag
$href_regex .="\s*";         // 2 zero or more whitespace
$href_regex .="a";           // 3 the a of the <a> tag itself
$href_regex .="\s+";         // 4 one or more whitespace
$href_regex .="[^>]*";       // 5 zero or more of any character that is _not_ the end of the tag
$href_regex .="href";        // 6 the href bit of the tag
$href_regex .="\s*";         // 7 zero or more whitespace
$href_regex .="=";           // 8 the = of the tag
$href_regex .="\s*";         // 9 zero or more whitespace
$href_regex .="[\"']?";      // 10 none or one of " or '
$href_regex .="(";           // 11 opening parenthesis, start of the bit we want to capture
$href_regex .="[^\"' >]+";   // 12 one or more of any character _except_ our closing characters
$href_regex .=")";           // 13 closing parenthesis, end of the bit we want to capture
$href_regex .="[\"' >]";     // 14 closing chartacters of the bit we want to capture
 
$regex  = "/";         // regex start delimiter
$regex .= $href_regex; //
$regex .= "/";         // regex end delimiter
$regex .= "i";         // Pattern Modifier - makes regex case insensative
$regex .= "s";         // Pattern Modifier - makes a dot metacharater in the pattern 
            // match all characters, including newlines
$regex .= "U";         // Pattern Modifier - makes the regex ungready
 
$html = "<A href=\"http://apnews.excite.com/article/20041226/D877FSF80.html\" target=_top>
<B>Asia Quakes' Tsunamis Kill More Than 8,000</B></A><BR>JAKARTA, Indonesia (AP) - 
The world's most powerful earthquake in 40 years struck deep under the Indian Ocean off the 
west coast of Sumatra on Sunday, triggering tidal waves up to 20 feet high that obliterated 
villages and seaside resorts in six countries across southern and southeast Asia. At least 
8,000 people were killed in the devastation.
<A href=\"http://apnews.excite.com/article/20041226/D877G5BO0.html\" target=_top>
<B>All Exit Polls Give Yushchenko Major Lead</B></A><BR>KIEV, Ukraine (AP) - All three exit 
polls tracking Sunday's presidential election in Ukraine gave opposition candidate Viktor 
Yushchenko a commanding lead of at least 15 percent.";
 
if (preg_match_all($regex, $html, $links)) {
 
 print("<P>Links: <pre>");
 print_r($links[1]);
 print("</pre></P>");
     }
 
else {
     print("No links.");
     }
/*
   $links[1] now has all the href links from $html
*/
 
?>