0

i am trying to fetch only image from database.In database the table (post_content) have image along with description i only want image.is it possible?Keep in mind that $row['post_content'] has image and decription.

<?php
   $sql = "select * from wp_tableposts;";
   $res = mysql_query($sql);
   while ($row = mysql_fetch_array($res))
   { echo'Post Contant:'. $row['post_content']. '';}
 ?> 
2
Contributors
2
Replies
19
Views
1 Year
Discussion Span
Last Post by Safina_1
1

Is it stored as HTML with an <img> tag? If affirmative then you could use a regular expression to extract the image link. For example:

$content = '
    <p>Title</p>
    <div><img class="hello" src="/images/ocean001.jpg" id="img"></div>
    <p>Blue</p>
';

$pattern = '/<img[^>]*src[\s]?=[\s]?["\']?([^"\']*)[^>]*>/i';

preg_match($pattern, $content, $matches);
print_r($matches);

It should return:

 Array
(
    [0] => <img class="hello" src="/images/ocean001.jpg" id="img">
    [1] => /images/ocean001.jpg
)

So in your loop:

$pattern = '/<img[^>]*src[\s]?=[\s]?["\']?([^"\']*)[^>]*>/i';

while ($row = mysql_fetch_array($res))
{
    preg_match($pattern, $row['post_content'], $matches);
    echo'Post Content:' . $matches[1];
}

And replace 1 with 0 if you want the tag. It will be slow. An alternative is to use a DOM library, but in this case you should parse a full document, not a part. If you can, try to separate description from image link before inserting them into the database, and set them together when needed.

Votes + Comments
thanks, you have done this
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.