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.

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='...'){
 if(strlen($text)>$maxchar){
  $words=explode(" ",$text);
  $output = '';
  $i=0;
  while(1){
   $length = (strlen($output)+strlen($words[$i]));
   if($length>$maxchar){
    break;
   }else{
    $output = $output." ".$words[$i];
    ++$i;
   };
  };
 }else{
  $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, networking, learning, and sharing knowledge.