0

I need to find the first image tag in a MySQL query, in a field called html (containing the HTML of the blog post. Here is the query and while loop I am using...

$query = mysqli_query($dbleads, "SELECT title, html FROM plugin_blog ORDER BY date_added DESC");

while ($row=mysqli_fetch_array($query)){
    $i = 1;
    $i++;
    ?> 
     <!-- echo $row['title'] to be replaced with first image tag in html column -->
     <div class="masonryImage" style="width: 300px; height:250px;"> <? echo $row['title']; ?></div> <?
    if ($i%2 == 0) { ?>
        <div class="masonryImage tweets" style="width:300px; height:175px;"><div class="tweet-content"><? echo $value['text']; ?></div></div>
    <?
    }
  }
// extra parentesis from previous loop from Twitter, meant to be here
}

I am thinking something like preg_match('/(<img[^>]+>)/i', $str, $matches), as found from this question, however, not sure how to implement it in this database query.

Thanks!

Community
  • 1
  • 1
Matt Maclennan
  • 1,266
  • 13
  • 40
  • Why not just get html with the query as normal and then do your regex in php – allen213 Oct 03 '13 at 10:21
  • You shouldn't break out of PHP every time. Just `echo` it and break out of the `echo`. Also, `$i += 1` and `++$i` are faster than `$i++` – yoeriboven Oct 03 '13 at 10:31

3 Answers3

1
while ($row=mysqli_fetch_array($query)){
    $i = 1;
    $i++;

    preg_match('/(<img[^>]+>)/i', $row['html'], $matches);
    $img = $matches[1];

    if($img) {
        echo $img;
    } else {
        // else goes here
    }

?> 
    <!-- echo $row['title'] to be replaced with first image tag in html column -->
    <div class="masonryImage" style="width: 300px; height:250px;"> <? echo $row['title']; ?></div> <?
    ...
1

I'm not even sure if it is possible, but if it is, it is a bad thing to do. Searching for the img-tag is though on the database and is way faster if it is done in PHP. So (if your preg_match is correct) do it like this:

preg_match('/(<img[^>]+>)/i', $str, $matches);

if ($matches[0]){
    echo $matches[0];
}
yoeriboven
  • 3,541
  • 3
  • 25
  • 40
0
preg_match('/(<img[^>]+>)/i', $row['html'], $matches);

if($matches) {
    $img = $matches[0];
} else {
    // set value $img here
}
Andronicus
  • 25,419
  • 17
  • 47
  • 88