Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate a string to first n characters of a string and add three dots if any characters are removed

How can I get the first n characters of a string in PHP? What's the fastest way to trim a string to a specific number of characters, and append '...' if needed?

like image 613
Alex Avatar asked Jul 01 '10 21:07

Alex


People also ask

How do you get the first n characters of a string?

To access the first n characters of a string in Java, we can use the built-in substring() method by passing 0, n as an arguments to it. 0 is the first character index (that is start position), n is the number of characters we need to get from a string. Note: The extraction starts at index 0 and ends before index 3.

How do you split the first 5 characters of a string?

You can use the substr function like this: echo substr($myStr, 0, 5); The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.

What is TRIM function in PHP?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string.


1 Answers

//The simple version for 10 Characters from the beginning of the string $string = substr($string,0,10).'...'; 

Update:

Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):

$string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string; 

So you will get a string of max 13 characters; either 13 (or less) normal characters or 10 characters followed by '...'

Update 2:

Or as function:

function truncate($string, $length, $dots = "...") {     return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string; } 

Update 3:

It's been a while since I wrote this answer and I don't actually use this code any more. I prefer this function which prevents breaking the string in the middle of a word using the wordwrap function:

function truncate($string,$length=100,$append="…") {   $string = trim($string);    if(strlen($string) > $length) {     $string = wordwrap($string, $length);     $string = explode("\n", $string, 2);     $string = $string[0] . $append;   }    return $string; } 
like image 185
Brendan Bullen Avatar answered Sep 21 '22 14:09

Brendan Bullen