BigToach.com

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($excerpt0strrpos(substr($excerpt0$length), ' '));
    
$exhausted false;
    foreach(
$matches[0] as $match)
    {
        if(
strpos($excerpt'|!|') !== false)
        {
            
$excerpt preg_replace('/\|\!\|/'$match$excerpt1);
        }
        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($str80);

// 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>
?>

Added on Jun 12th at 2 pm by Scott - 0 Comments


0 Responses to excerpt

Name:

Site or Mail:

Comment:

To try to reduce the ammount of spam, please enter the word GOOSE in the following form

Security Code: