Custom Web Applications to Grow Your Business

(256) 429-8145

How to extract images from html content in php and display excerpt

There are many ways of extracting an image from content with php, but recently I was working on a project and I wanted an easy way to extract without too much work, too much coding, that is. The idea was to access a database and display content in excerpt form with 100px by 75px thumbnail images extracted from the content. We will use the while loop to display to display a number of articles php image extraction getting image from content in php // first connect to database // then run mysql_query $result = mysql_query("SELECT * FROM table"); if (!$result) { exit ('Error fethcing member details: ' . mysql_error(). ''); } // run while loop while ($row = mysql_fetch_array($result)) { $title = $row ['title']; $link = $row ['link']; $html = $body; // clean text to have neatly displayed content $body = strip_tags(trim($body)); <strong>// get image from content by performing a regular expression</strong> <pre>if (stripos($html, '&lt;img') !== false) { preg_match('/&lt;img[^&gt;]+&gt;/i',$html, $matches);</pre> foreach ($matches as $var){ echo $var; } } else { // else echo an alternative image, so an image is always displayed if the article does not have one echo '<a href="'.$url.'.html"><img src="alternate_image.jpg" alt="" /></a>'; } // finish getting image // display title echo $title'; // display body as excerpt with only 450 characters echo ''.substr($body, 0, strpos("$body", " ", "450")).'...'; // div with clear for neat display of content echo ''; }