PHP Snippets
excerpt
Information
(PHP Version >= 3)Functions used in this snippet: preg_match_all, preg_replace, substr, strrpos, strpos.
Description
str excerpt( str excerpt, int length )
Returns an excerpt of the string excerpt with a maximum length of length. This function is useful if you have HTML in the excerpt because it will keep the HTML structure intact. It does this by keeping the HTML tags in the excerpt, and appending the empty HTML tags at the end of the excerpt.
Snippet
<?php
function excerpt($excerpt, $length)
{
preg_match_all('/<[^>]+>/', $excerpt, $matches);
$excerpt = preg_replace('/<[^>]+>/', '|!|', $excerpt);
$excerpt = substr($excerpt, 0, strrpos(substr($excerpt, 0, $length), ' '));
$exhausted = false;
foreach($matches[0] as $match)
{
if(strpos($excerpt, '|!|') !== false)
{
$excerpt = preg_replace('/\|\!\|/', $match, $excerpt, 1);
}
else
{
if(!$exhausted)
{
$excerpt .= '...';
$exhausted = true;
}
$excerpt .= $match;
}
}
return $excerpt;
}
?>
Example
excerpt Can be used in the following way:
<?php
$str = '<p>Hello <a href="http://www.bigtoach.com">Test</a> This is just a test to see if <strong>Nested</strong> <em>Tags</em> <em>Will work</em></p>';
echo excerpt($str, 80);
// Produces The Following
// <p>Hello <a href="http://www.bigtoach.com">Test</a> This is just a test to see if <strong>Nested</strong> <em>Tags</em>...<em></em></p>
?>
0 Responses to excerpt