From 43bc39d425001b20ea9e679c665c09c6fead8035 Mon Sep 17 00:00:00 2001 From: Joshua Ramon Enslin Date: Fri, 23 Oct 2020 16:13:02 +0200 Subject: [PATCH] Add function createTextSnippet() for shortening text to an expected length Close #1 --- MD_STD.php | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/MD_STD.php b/MD_STD.php index 3c761b9..262721c 100644 --- a/MD_STD.php +++ b/MD_STD.php @@ -356,4 +356,26 @@ final class MD_STD { } + /** + * This function cuts down a string and adds a period in case it's longer + * than length to create a snippet. + * + * @param string $string Input text to cut down. + * @param integer $length Length of the snippet to create. + * + * @return string + */ + public static function createTextSnippet(string $string, int $length = 180):string { + + if (\mb_strlen($string) > $length) { + $string = \mb_substr($string, 0, $length); + if (($lastWhitespace = \mb_strrpos($string, ' ')) !== false) { + $string = \mb_substr($string, 0, $lastWhitespace); + } + $string .= '...'; + } + return $string; + + } + }