Shortening a string with … on the end

倖福魔咒の 提交于 2019-12-11 06:26:04

问题


Is there an official PHP function to do this? What is this action called?


回答1:


No, there is no built-in function, but you can of course build your own:

function str_truncate($str, $length) {
   if(strlen($str) <= $length) return $str;
   return substr($str, 0, $length - 3) . '...';
}



回答2:


function truncateWords($input, $numwords, $padding="") {
    $output = strtok($input, " \n");
    while(--$numwords > 0) $output .= " " . strtok(" \n");
    if($output != $input) $output .= $padding;
    return $output;
}

Truncate by word




回答3:


No, PHP does not have a function built-in to "truncate" strings (unless some weird extension has one, but it's not guaranteed the viewers/you will have that sort of plugin -- I don't know of any that do).

I would recommend just writing a simple function for it, something like:

<?php

function truncate($str, $len)
{
  if(strlen($str) <= $len) return $str;
  $str = substr($str, 0, $len) . "...";
  return $str;
}

?>

And if you'd like to use a "suspension point" character (a single character with the three dots; it's unicode), use the HTML entity &hellip;.




回答4:


I use a combination of wordwrap, substr and strpos to make sure it doesn't cut off words, or that the delimiter is not preceded by a space.

function truncate($str, $length, $delimiter = '...') {
   $ww = wordwrap($str, $length, "\n");
   return substr($ww, 0, strpos($ww, "\n")).$delimiter;
}

$str = 'The quick brown fox jumped over the lazy dog.';
echo truncate($str, 25); 
// outputs 'The quick brown fox...' 
// as opposed to 'The quick brown fox jumpe...' when using substr() only


来源:https://stackoverflow.com/questions/4474517/shortening-a-string-with-on-the-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!