Add function createTextSnippet() for shortening text to an expected

length

Close #1
This commit is contained in:
Joshua Ramon Enslin 2020-10-23 16:13:02 +02:00 committed by Stefan Rohde-Enslin
parent 711bd49048
commit 43bc39d425
Signed by: jrenslin
GPG Key ID: 46016F84501B70AE

View File

@ -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;
}
}