I have a function which looks through a string of text for <image0n> and replaces it with a full <img> tag. I need to use the number after "<image" to pull some attributes from the database. The trouble I'm having is that when using preg_replace, the function only uses the first number it pulls. I think I need to do a "for" of "while" loop, but can't figure out how. Any suggestions for how to do a database query for each instance of the matched pattern?
$enid is the entry id for the text string.
$enid = "1";
$string = "testing header
<image01>
as;dlk,
<image02>
asdkjhhjkl
while <image03>you were out";
function imageLinks($string, $enid){
global $site_root,
$dir_path;
$pattern = "/<image([0-9]{2})>/"; //pattern for preg
preg_match($pattern,$string,$matches); // get image number for use in query
$image_number = $matches[1];
$file_name = "$enid"."_$image_number".".jpg";
$query="SELECT width, height, caption //select image attributes from database
FROM image
WHERE file_name = '$file_name'";
$results = mysql_query($query) or die ("Error in query: $query. " .mysql_error()); // the query.
$row = mysql_fetch_array($results);
$width = $row[0];
$height = $row[1];
$caption = $row[2];
//replacement pattern for preg
$replacement = "<p>\n<a href=\"$dir_path"."$enid"."_$1"."_lg".".jpg\">";
$replacement .= "\n<img src=\"$dir_path"."$enid"."_$1".".jpg\" ";
$replacement .= "alt=\"$caption\" border=\"1\" width=\"$width\" height=\"$height\" />\n";
$replacement .= "</a>\n";
$replacement .= "<br /><span class=\"caption>$caption</span></p>";
echo(preg_replace($pattern, $replacement, $string));
//return $string;
}
imageLinks($string,$enid); // run function