Skip to content

Instantly share code, notes, and snippets.

@marcoscoelho
Created August 25, 2011 07:22
Show Gist options
  • Save marcoscoelho/1170155 to your computer and use it in GitHub Desktop.
Save marcoscoelho/1170155 to your computer and use it in GitHub Desktop.
This function is similar to two native functions from CI (ellipsize and character_limiter) but more ruthless (non-preserves words), flexible (dont alters or strip anything in your string, because you can do it easily if necessary) and accurate (passed in
<?php defined('BASEPATH') OR exit('No direct script access allowed.');
/**
* Character Limiter Mid
*
* Limits the string representing the characters removed from somewhere from
* their mid. This limiter considers the output string as two parts (start and
* end) and not preserves complete words, so you also can chose exactly how many
* characters at start and end you need have.
*
* @access public
* @param string The input string
* @param mixed Limit count (eg. 20) or an array assigning lengths of start and end (eg.: array(15, 5)) to your output
* @param string The mid character. Usually an ellipsis
* @return string
*/
function character_limiter_mid($str, $n = 20, $mid_char = '&#8230;')
{
// Getting params
// @param int $n Number of max lenght
// @param int $a Length of start part
// @param int $b Length of end part
if (is_array($n) && sizeof($n = array_filter($n, 'is_numeric')) === 2)
{
list($a, $b) = $n;
$n = array_sum($n);
}
elseif (is_numeric($n))
{
$a = ceil($n/2);
$b = $n-$a;
}
// Are anything to do?
if (isset($a, $b) && $n > 0)
{
// Is the string long enough to be limited?
if (strlen($str) > (strlen($mid_char)+$n))
{
// No has end part?
if ($b <= 0)
{
$str = substr($str, 0, $a) . rtrim($mid_char);
}
// No has first part?
elseif ($a <= 0)
{
$str = ltrim($mid_char) . substr($str, -$b);
}
// Has both parts!
else {
$str = substr_replace($str, $mid_char, $a, -$b);
}
}
// Work completes!
return $str;
}
}
/* End of file text_helper.php */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment