Home  >  Article  >  Backend Development  >  An example of PHP code that truncates text at character breakpoints

An example of PHP code that truncates text at character breakpoints

WBOY
WBOYOriginal
2016-07-25 08:58:50902browse
  1. //The so-called word break is where a word can be broken when changing lines. This function will truncate the string at hyphenation points.
  2. // Please acknowledge use of this code by including this header.
  3. function myTruncate($string, $limit, $break=".", $pad="...") {
  4. // return with no change if string is shorter than $limit
  5. if(strlen($string) <= $limit)
  6. return $string;
  7. // is $break present between $limit and the end of the string?
  8. if(false !== ($ breakpoint = strpos($string, $break, $limit))) {
  9. if($breakpoint < strlen($string) - 1) {
  10. $string = substr($string, 0, $breakpoint) . $pad;
  11. }
  12. }
  13. return $string;
  14. }
  15. /***** Example ****/
  16. $short_string=myTruncate($long_string, 100, ' ');
  17. ?>
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn