-
-
Save tommcfarlin/97c336e3e7246c9d5f6d46684ff1e6e9 to your computer and use it in GitHub Desktop.
[PHP] How to Easily Truncate Text in PHP
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 | |
/** | |
* Truncates the specified text to the specified length to the last whole word and | |
* adds ellipses to the end of the truncated string. | |
* | |
* @param string $text The text to truncate. | |
* @param int $length The maximum allowed length of the text. | |
* @return string The text if it's less than the length of the specified length or the text truncated to the specified length. | |
*/ | |
public function truncate($text, $length) | |
{ | |
if ($length >= \strlen($text)) { | |
return $text; | |
} | |
return preg_replace( | |
"/^(.{1,$length})(\s.*|$)/s", | |
'\\1...', | |
$text | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment