Forum Moderators: coopster

Message Too Old, No Replies

Using Preg Match whilst trying to display images in article

Seem to be stuck!

         

The Cricketer

4:14 pm on Aug 1, 2005 (gmt 0)

10+ Year Member



Below are the numbered steps that I need to recreate in order to adequately display images in my article.

1) Pull page's main article content from DB and assign to variable: $text
2) Extract the filename text from between [pic][/pic] tags example: from [pic]10.jpg[/pic] to 10.jpg
3) Pull image's corralating caption from DB.
4) Replace [pic]10.jpg[/pic] with relevent HTML
5) Repeat process for all [pic][/pic] tags within $text
6) Display content

I've had a stab at this but haven't been entirely successful yet.[b]

1) Done. $text = $row['main_text'];

2) preg_match_all ("/\[pic\](.*?)\[\/pic\]/", $text, $matches);
for ($i=0; $i< count($matches[0]); $i++) {
$matches[1][$i];

3) ***NOT SURE ABOUT THIS*****
$sql[$i] = "SELECT * FROM gallery_photos WHERE photo_filename = ".$matches[1][$i];}

4) $text = preg_replace( "/\[pic\](.*?)\[\/pic\]/", "<div class=\"right\"><img src=\"/imagescripts/phpThumb.php?src=/photos/\\1&w=150\" /></div>", $text );

5) ***NOT SURE ABOUT THIS*****

6) echo $text;

[b]Can anyone try and advise me on the nest approach here please.

The Cricketer

9:10 am on Aug 2, 2005 (gmt 0)

10+ Year Member



Well I've had a stab at this on my own, unbelievable. The code below works and does what I want. If you can understand it, is there a more efficient way to code it?

preg_match_all ("/\[pic\](.*?)\[\/pic\]/", $text, $matches);

for ($i=0; $i< count($matches[0]); $i++) {
$fetch[$i] = "SELECT * FROM gallery_photos WHERE photo_filename = '".$matches[1][$i]."'";

$result = mysql_query($fetch[$i], $conn) or die ('Failed to execute ' . $fetch[$i] . ' due to ' . mysql_error());

$row = mysql_fetch_array($result) or die ('Failed to get data due to ' . mysql_error());

$match = $matches[0][$i];
$match2 = $matches[1][$i];

$text = preg_replace( "/\[pic\]".$match2."\[\/pic\]/", "<div class=\"right\"><img src=\"/imagescripts/phpThumb.php?src=/photos/".$match2."&w=150\" /><h3 class=\"caption\">".$row['photo_caption']."</h3></div>", $text );

echo $text;

dcrombie

11:00 am on Aug 2, 2005 (gmt 0)



This should get you on the right track:

function showPic($imgname)  
{
return "( INSERT IMAGE $imgname )";
}

$text = preg_replace("/\[pic\]([^\[]+)\[\/pic\]/e", "showPic('\\1')", $text);

;)