Skip to content

Instantly share code, notes, and snippets.

@mcordingley
Last active June 21, 2017 15:53
Show Gist options
  • Save mcordingley/f43124a42389f416193ab9a378e2fe4b to your computer and use it in GitHub Desktop.
Save mcordingley/f43124a42389f416193ab9a378e2fe4b to your computer and use it in GitHub Desktop.
<?php
/**
* @param string $message
* @param int $length
* @param string $cap What to place at the end of the truncated message to indicate truncation.
* @param string $delimiter
* @param bool $removeLastDelimiter
* @param bool $lengthInBytes
* @param string|null $encoding
* @return string
*/
function truncate(string $message, int $length, string $cap, string $delimiter = ' ', bool $removeLastDelimiter = true, bool $lengthInBytes = false, string $encoding = null): string
{
if ($encoding === null) {
$encoding = mb_internal_encoding();
}
if (($lengthInBytes ? strlen($message) : mb_strlen($message, $encoding)) <= $length) {
return $message;
}
$firstCut = $lengthInBytes ?
mb_strcut($message, 0, $length - strlen($cap), $encoding) :
mb_substr($message, 0, $length - mb_strlen($cap, $encoding), $encoding);
$lastDelimiter = mb_strrpos($firstCut, $delimiter, $encoding);
return mb_substr($firstCut, 0, $removeLastDelimiter ? $lastDelimiter : $lastDelimiter + mb_strlen($delimiter, $encoding)) . $cap;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment