How to cut (string) text after (x) amount of characters

You have long texts (string) and you want to display limited characters for introtext and readmore button to see details.

how-to-cut-your-texts-limited-with-x-characters

Some time you see anywhere with questions like that:

 40 down vote favorite 18       What’s the fastest way to trim a string to a specific number of characters, and append ‘…’ if needed?
How can I extract mid section of the string which is always 5 characters long and is always followed by a period “.” ?

have a text that i get with the php variable $text. This text can be 100 or 1000 or 10000 words. My page would extend based on the text but if the text is like 10000 the page looks ugly. I want to get the length of the text and limit the number of characters to maybe 500 and provide a link saying ‘Read more’, if the text length is > 500 and in this link Read More, it will show a pop with all the text in $text. I need some help with this.

What is best solution:

Some people use like that for his php code
$string = "This is a large text for demonstrations purposes";
if(strlen($string) > 20) $string = substr($string, 0, 20).'...';
echo $string;

Or

function split_words($string, $nb_caracs, $separator){
    $string = strip_tags(html_entity_decode($string));
    if( strlen($string) <= $nb_caracs ){
        $final_string = $string;
    } else {
        $final_string = "";
        $words = explode(" ", $string);
        foreach( $words as $value ){
            if( strlen($final_string . " " . $value) < $nb_caracs ){
                if( !empty($final_string) ) $final_string .= " ";
                $final_string .= $value;
            } else {
                break;
            }
        }
        $final_string .= $separator;
    }
    return $final_string;
}

With Joomla content readmore for some News Module display to use like that

$content = $this->item->text;//or $item->text
$content = str_replace(']]>', ']]>', $content);
$content = strip_tags($content);
//Number of your character
$max_char = 100;
if ((strlen($content)>$max_char) && ($espacio = strpos($content, " ", $max_char )))
{
$content = substr($content, 0, $espacio);
echo $content;
echo "...";
} else(
echo $content;
)

With WordPress we use Like that

$content_description = trim(get_the_excerpt($post->ID));
$content_description = strip_tags(str_replace(']]>', ']]>', $content_description));
$max_char = 250;
if ((strlen($content_description)>$max_char) && ($espacio = strpos($content_description, " ", $max_char ))){
$content_description = substr($content_description, 0, $espacio);
}

Googluck

Be Sociable, Share!

Leave a comment