Show DevBest [PHP] Truncate String

Status
Not open for further replies.

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,638
2,393
I know this is very basic, but it seems to be a common question that people ask me: "how to truncate a string in PHP" -- basically, how do I cut a string after a certain length?

Well it's simple, I created a function for you all to use if you wish that will cut a string off after a certain length that you choose.

The usage is very easy and is demonstrated in the code snippet below:

PHP:
<?php
function truncate( $str, $allowed_length=10 )
{
    return substr( trim( $str ), 0, $allowed_length ); //return the truncated value
}
 
echo truncate( "Mark Eriksson is the best person ever!" ); //output: Mark Eriks
echo truncate( "Mark Eriksson is the best person ever!", 25 ); //output: Mark Eriksson is the best
?>

I hope that this helps you if you choose to use it.

Mark.
 

Kryptos

prjRev.com
Jul 21, 2010
2,205
1,252
I like how you create all these useful functions.

Do you have a list of them all ( I think you have a downloads page )? I think I will add them all to my common functions file :)
 

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,638
2,393
I like how you create all these useful functions.

Do you have a list of them all ( I think you have a downloads page )? I think I will add them all to my common functions file :)
I have this:
But I might make a list of somewhat-useful PHP functions I've made so people can copy them. Good idea.

Made a few changes, you can now choose to remove white-space without it doing it automatically, and you can have something following the truncated string, for example: "..."

PHP:
<?php 
function truncate( $str, $allowed_length=10, $remove_spaces=false, $after_str="" ) 
{ 
    /*
        $str - the string to truncate
        $allowed_length - the amount of characters to limit to
        $remove_spaces - use trim() to remove white-space
        $after_str - another string to appear after the truncation, could be '...' if you like, so you could have a snippet of a story with "..." at the end
    */
    $str = ( $remove_spaces == true ) ? trim( $str ) : $str;
    
    $return = substr( $str, 0, $allowed_length );
    if ( !empty( $after_str ) ) $return .= $after_str;
    
    return $return;
} 
 
echo truncate( "Mark Eriksson is the best person ever!" ); //output: Mark Eriks 
echo truncate( "Mark Eriksson is the best person ever!", 25 ); //output: Mark Eriksson is the best
echo truncate( "Mark Eriksson is the best person ever!", 25, false, "..." ); //output: Mark Eriksson is the best...
echo truncate( "   Mark Eriksson is the best person ever!  ", 20, true, "..." ); //output: Mark Eriksson is the...
?>
 
Status
Not open for further replies.

Users who are viewing this thread

Top