Skip to content

Instantly share code, notes, and snippets.

@meSingh
Created July 1, 2013 13:32
Show Gist options
  • Save meSingh/5900786 to your computer and use it in GitHub Desktop.
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.
<?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