Created
July 1, 2013 13:32
-
-
Save meSingh/5900786 to your computer and use it in GitHub Desktop.
Cut a string on a specific length or make the long string shorter in php with spaces support.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* | |
* Make the string of a defined length | |
* | |
* @param string $string | |
* @param integer $max_length | |
* @param boolean $trunc_at_space | |
* @param string $replacement | |
* @return Short String | |
* | |
*/ | |
public function do_truncate($string, $max_length = 30, $trunc_at_space = false, $replacement = '') | |
{ | |
$max_length -= strlen($replacement); | |
$string_length = strlen($string); | |
if($string_length <= $max_length) | |
return $string; | |
if( $trunc_at_space && ($space_position = strrpos($string, ' ', $max_length-$string_length)) ) | |
$max_length = $space_position; | |
return substr_replace($string, $replacement, $max_length); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment