Created
August 27, 2013 05:12
-
-
Save jrmadsen67/6349826 to your computer and use it in GitHub Desktop.
MY_text_helper - very quick & dirty version of the character_limiter() that allows you to set a hard limit on the length and it will roll back the last word
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 | |
/** | |
* Character Limiter | |
* | |
* Limits the string based on the character count. Preserves complete words | |
* so the character count may not be exactly as specified. | |
* | |
* @access public | |
* @param string | |
* @param integer | |
* @param string the end character. Usually an ellipsis | |
* @return string | |
*/ | |
if ( ! function_exists('character_limiter')) | |
{ | |
function character_limiter($str, $n = 500, $end_char = '…', $hard_limit=false) | |
{ | |
if (strlen($str) < $n) | |
{ | |
return $str; | |
} | |
$str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str)); | |
if (strlen($str) <= $n) | |
{ | |
return $str; | |
} | |
$out = ""; | |
foreach (explode(' ', trim($str)) as $val) | |
{ | |
if ($hard_limit && strlen($out.$val) >= $n) | |
{ | |
return (strlen($out) == strlen($str)) ? $out : $out.$end_char; | |
} | |
$out .= $val.' '; | |
if (strlen($out) >= $n) | |
{ | |
$out = trim($out); | |
return (strlen($out) == strlen($str)) ? $out : $out.$end_char; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment