Return to Snippet

Revision: 10285
at December 16, 2008 05:45 by gauravjassal


Initial Code
<?php
function ellipsis($text, $maxChars = 20, $splitter = '...')
{
    $theReturn = $text;
    $lastSpace = false;

    if (strlen($text) > $maxChars)
    {
        $theReturn = substr($text, 0, $maxChars - 1);

        if (in_array(substr($text, $maxChars - 1, 1),array(' ', '.', '!', '?')))
        {
            $theReturn .= substr($text, $maxChars, 1);
        }
        else
        {
            $theReturn = substr($theReturn, 0, $maxChars - strlen($splitter));
            $lastSpace = strrpos($theReturn, ' ');

            if ($lastSpace !== false)
           {
                $theReturn = substr($theReturn, 0, $lastSpace);
           }

            if (in_array(substr($theReturn, -1, 1), array(',')))
            {
                $theReturn = substr($theReturn, 0, -1);
            }
            $theReturn .= $splitter;
        }
    }
    return $theReturn;
}
?>

<?php 
$text = "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo."; 
echo ellipsis($text,150); 
?>

Initial URL

                                

Initial Description

                                

Initial Title
Creating an Ellipsis in PHP

Initial Tags

                                

Initial Language
PHP