Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
backend-tech:php:favorite-php-snippets:itrunc [Jul 6, 2026 02:53 AM]
47.15.233.30 removed
— (current)
Line 1: Line 1:
-= String Truncation - iTrunc() = 
  
-A great string truncation function, originally from [[http://feedcreator.org/|FeedCreator]]  (GPL). 
- 
- 
-<code php> 
-/** 
- * Truncates a string to a certain length at the most sensible point. 
- * First, if there's a '.' character near the end of the string, the string is truncated after this character. 
- * If there is no '.', the string is truncated after the last ' ' character. 
- * If the string is truncated, " ..." is appended. 
- * If the string is already shorter than $length, it is returned unchanged. 
- * 
- * @static 
- * @param string    string A string to be truncated. 
- * @param int        length the maximum length the string should be truncated to 
- * @return string    the truncated string 
- */ 
-function _iTrunc($string, $length) { 
-    if (strlen($string)<=$length) { 
-        return $string; 
-    } 
- 
-    $pos = strrpos($string,"."); 
-    if ($pos>=$length-4) { 
-        $string = substr($string,0,$length-4); 
-        $pos = strrpos($string,"."); 
-    } 
-    if ($pos>=$length*0.4) { 
-        return substr($string,0,$pos+1)." ..."; 
-    } 
- 
-    $pos = strrpos($string," "); 
-    if ($pos>=$length-4) { 
-        $string = substr($string,0,$length-4); 
-        $pos = strrpos($string," "); 
-    } 
-    if ($pos>=$length*0.4) { 
-        return substr($string,0,$pos)." ..."; 
-    } 
- 
-    return substr($string,0,$length-4)." ..."; 
- 
-} 
-</code>