At a guess, you probably want to use preg_match_all() instead of preg_match(). Also, you'll want to use the 3rd parameter to that function to specify the array variable that stores the results, as both functions only return the number of matches, not the actual matches.
preg_match_all('/your_regular_expression/', $contents, $links);
Then when you loop on it, all the full matches will be a sub-array in $links[0], so your foreach would be:
foreach($links[0] as $link) {