Wednesday, 3 June 2015

truncate string with optional suffix

tstr - truncate string It accepts three arguments( two required and one optional ) Returns the truncated string if the string is longer than the length specified. If the length of suffix is bigger than required length of string, than it will print and error.
<?php /* 
*    @param $str - required - string to be truncated 
*    @param $length - required - length of required portion of string 
*    @suffix - optional - the suffix that you want at the end of string if string is longer than $length 
*    @returns - truncated string 
*/ 
function tstr($str$length$suffix=""){ 
    
$valid_min_length 1; 
    if(
strlen($str) > $length){ 
        if(
$suffix != "") 
            
$valid_min_length strlen($suffix) + $valid_min_length; 
        if(
$length $valid_min_length){ 
            die(
"Either increase the length of truncated string required or reduce the suffix."); 
        } 
        
$str substr($str0, ($length strlen($suffix))).$suffix; 
    } 
    return 
$str; 
} 
?>

0 comments:

Post a Comment