Created
January 13, 2013 19:19
-
-
Save krciga22/4525755 to your computer and use it in GitHub Desktop.
Truncate String PHP Snippet: truncate a string in PHP either by setting a maximum length or maximum number of words. Also includes the ability to append a suffix if the string is truncated.
This file contains hidden or 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 | |
function truncate($text, $suffix="...",$maxLength=false,$maxWords=false){ | |
$text = trim($text); | |
$text = preg_replace("/[\s]+/", " ", $text); // convert all consecuritve spaces to single spaces | |
if($maxLength!==false){ | |
if(strlen($text)>$maxLength){ | |
$text = substr($text, 0, $maxLength).$suffix; | |
} | |
} | |
if($maxWords!==false){ | |
$textArray = explode(' ', $text); | |
if(count($textArray)>$maxWords){ | |
$textArray = array_splice($textArray, 0, $maxWords); | |
$text = implode(' ', $textArray).$suffix; | |
} | |
} | |
return($text); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment