Pull first image from a description field

I have a table that currently has title,description,category
basically what I want to do is retrieve the first image from each description field it is embedded within text(they all contain at least one image ), to use as thumbnails for each result.

here is the code I use to retrieve the data.


<?php

$sql = 'SELECT DISTINCT * FROM table WHERE category="cargo" and status="Active" LIMIT 2';

$sql2 = mysql_query($sql,$connection) or die(mysql_error());

?>

<div class="rectanglebox">

				<h3>CARGO</h3>

				<ul><?php

	while($row=mysql_fetch_assoc($sql2)){

?>

<a href="http://www.website-address.com/<?php echo $row['category']; ?>/<?php echo $row['title']; ?>/<?php  echo $row['id'];   ?>/.html"><li><?php echo $row['title']; ?></li></a>

	<?php

	}

?>


my question is how can I pull the first image from the “description” field from each of the results ?

I don’t know how is your img tag structure, but you can use the following code to get the source of first img:

$matches=array();
preg_match("/<img(.*?)src=\\"(.*?)\\"(.*?)>/s",$row,$matches);

It doesnt seem to pull anything, this is my image tag code from the description field:

<img class=“aligncenter size-full wp-image-66917” title=“Vizio Cinema HDTV” src=“http://imagefile location.com.jpg” alt=“Vizio Cinema HDTV” width=“650” height=“397” />

I have checked with the following code and I can get the src of the string that contain image:


<?php
$img = '<img class="aligncenter size-full wp-image-66917" title="Vizio Cinema HDTV" src="http://imagefile location.com.jpg" alt="Vizio Cinema HDTV" width="650" height="397" />';
$matches=array();
preg_match("/<img(.*?)src=\\"(.*?)\\"(.*?)>/s",$img,$matches); 
print_r($matches);
?>

The src value will be stored in array element with index 2.

This is what I’m trying right now, and I get Array ( ) as a result


<?php

$sql = 'SELECT DISTINCT * FROM table WHERE category="cargo" and status="Active" LIMIT 2';

$sql2 = mysql_query($sql,$connection) or die(mysql_error());

?>

<div class="rectanglebox">

                <h3>CARGO</h3>

                <ul><?php

    while($row=mysql_fetch_assoc($sql2)){

    $desc= $row['description'];

?>

<?php
$img = $desc;
$matches=array();
preg_match("/<img(.*?)src=\\"(.*?)\\"(.*?)>/s",$img,$matches); 
print_r($matches);
?>

<a href="http://www.website-address.com/<?php echo $row['category']; ?>/<?php echo $row['title']; ?>/<?php  echo $row['id'];   ?>/.html"><li><?php echo $row['title']; ?></li></a>

    <?php

    }

?>


^^
I think this will pull the image if you already know what that image is, in my case the image is embedded with text in this field $desc= $row[‘description’];

The output array is just my sample for you to know how the preg_match return, it help you have the source of image and you can display it, right?