Forum Moderators: coopster

Message Too Old, No Replies

Help with preg_match to fetch image from code

         

vanner

9:14 am on Apr 18, 2006 (gmt 0)



I'm writing a script that snoops for an image on a webpage and prints it out from the source. Can someone help me out with the reg expression? Also, does my coding goin in the right direction with what I want to do?

<?php
// Fetch webpage
$url = file_get_contents('http://example.com/todays%5Fgirl/');

// Look for this image which is changed daily. <img src="/todays_girl/girls/*/*.jpg"

preg_match("/<img src=\"\/todays_girl\/girls\/([a-zA-Z_0-9]\/([a-zA-Z_0-9]\+.jpg)/i",$url, $matches);

$file = $matches[1];

echo '
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<img src="http://example.com/todays_girl/$file">
</head>
</html>';
?>

[edited by: coopster at 4:47 pm (utc) on April 18, 2006]
[edit reason] generalized url TOS [webmasterworld.com] [/edit]

coopster

1:13 pm on Apr 20, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, vanner.

Yes, your though process seems to be on track. You pull the page content down into a string variable, parse the string looking for a src attribute and capture it's value. The regular expression can be as simple as

$pattern = '/src=[\'"]?([^\'" >]+)[\'" >]/'; 
preg_match_all($pattern, $string, $matches);
print '<pre>'; print_r($matches); print '</pre>';
exit;