getButterfly Logo getButterfly code wrangling since 2005

It took me a while to try and rephrase the title, but to no avail.

Using the image.php script from my last article, I will read database entries and replace all tags with clickable thumbnails. All you need to do is have a database entry with an tag.

Read the database (I’m sure you know how to do this):

$sql = “SELECT * FROM articole WHERE post_id = ‘$id'”;
$result = mysql_query($sql);
$row = mysql_fetch_array($result);

Extract the image and preg_replace it:

$content = $row[‘content’];

$content = preg_replace(“/<img[^’]*?src=\”([^’]*?)\”[^’]*?>/”, ‘<a href=”$1″><img src=”image.php/$1?width=150&amp;height=150&amp;quality=100&amp;image=$1″ alt=”” /></a>’, $content);

echo $content;?>

The script wraps any image found in the content with an anchor and the image.php caller script. I guess you recognize the parameters from the previous article. What does $1 do? It replaces the first parameter of preg_replace with itself. Pretty easy, isn’t it?

Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.

If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a reply

Love programming?

Learn about the most amazing things. Get smarter everyday!