Hi i would like to know how i add the ... when you cut a string in php. For example a string gets cut that exceeds the character limit and gets added with ... You can find this anywhere like on youtube or any big media site. I have searched everywhere but could not find any help. I used the substr function and would like to know if there is any way to use that to get the three dots.

Recommended Answers

All 2 Replies

Perhaps the following function?

function trimstr($input,$length) {
if (strlen($input)>$length) {
return substr($input,$length).'...';
} else {
return $input;

echo trimstr('abcdefghijklmnopqrstuvwxyz',3);

I know that this thread is old but i needed the same thing and found a really nice solution.

$string = substr($string,0,30);

The string variable is now set to the following.

$string = 'This string is too long and wi';

This example highlights the major problem with this function in that it will take no notice of the words in a string. The solution is to create a new function that will avoid cutting words apart when cutting a string by a number of characters.

function substrwords($text,$maxchar,$end='...'){
  $words=explode(" ",$text);
  $output = '';
   $length = (strlen($output)+strlen($words[$i]));
    $output = $output." ".$words[$i];
  $output = $text;
 return $output.$end;

This function splits the string into words and then joins them back together again one by one. The good thing is that if there is a word that would make the string longer than the required number of characters it doesn’t include the word. The function can be called like this.

echo substrwords($string,30);

This produces the following output.

This string is too long and...
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.