0

I have a database with a column named images

it looks like:

[image1.jpg],[image2.jpg],[image3.jpg] etc

how can i extract this information and display each image using PHP like:

$sql="SELECT * from table ";
$rs=mysql_query($sql,$conn);
$result=mysql_fetch_array($rs);

echo '<img src="image1.jpg" />';
echo '<img src="image2.jpg" />';
echo '<img src="image3.jpg" />';
4
  • 4
    use explode function ? Commented Oct 10, 2013 at 20:43
  • 2
    explode on , loop eanch array entry trimming [].... and then consider normalizing your database Commented Oct 10, 2013 at 20:44
  • explode. As @MarkBaker mentioned in his comment. Commented Oct 10, 2013 at 20:45
  • this question might make your path :stackoverflow.com/questions/8075323/… Commented Oct 10, 2013 at 20:50

3 Answers 3

5
foreach(explode(',',$result['column']) as $image){
    echo '<img src='.strtr($image,'[]','""').' />';
}
Sign up to request clarification or add additional context in comments.

4 Comments

Think you're missing an ending ) on the strtr call
$images = explode(',',$result['column']); echo '<img src='.strtr($images[0],'[]','""').' />';
how can i get the img src to display like <img src="/img/project-gallery/image1.jpg" />
Sorry, but I don't understand. My previous comment prints out exactly this. I don't see any difference.
0

The easiest way will be regexp.

preg_match_all('/\[(.*?)\]/', $field, $images);
$images = $images[1];

Now $images will contain array of all found images.

2 Comments

Probably not easier, and certainly too heavyweight for the requirement.
@MikeW You can test it but I don't think it'll be much slower than other solutions in that case. If of course any difference will be noticeable.
0

You should use str_replace() & explode() functions to deal with this situation and avoid using regex:

<?php

$data = "[image1.jpg],[image2.jpg],[image3.jpg]";

$data = str_replace("]","", str_replace("[", "", $data));

$exploded = explode("," $data);

?>

The array will contain the images each in an element without the "[" and "]", now all you have to do is loop throught it and echo it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.