| @@ -18,8 +18,59 @@ | ||
| 18 | 18 | */ |
| 19 | 19 | abstract class JHtmlVikbooking |
| 20 | 20 | { |
| 21 | 21 | /** |
| 22 | + * Helper method used to obtain a shorten version of the given text. | |
| 23 | + * | |
| 24 | + * Even if a maximum threshold is provided, this doesn't mean that the | |
| 25 | + * length of the resulting text will be exactly equal to that amount. | |
| 26 | + * This beacuse the function doesn't break words. | |
| 27 | + * | |
| 28 | + * @param string $text The text to shorten. | |
| 29 | + * @param int|null $max The maximum number of allowed characters. | |
| 30 | + * | |
| 31 | + * @return string | |
| 32 | + * | |
| 33 | + * @since 1.8 | |
| 34 | + */ | |
| 35 | + public static function shorten(string $text, ?int $max = null): string | |
| 36 | + { | |
| 37 | + // add a white space after the closure of any tag | |
| 38 | + $text = preg_replace_callback("/(<\/[a-z0-9\-]+>)|(\s*\/\s*>)/", function($match) { | |
| 39 | + return $match[0] . " "; | |
| 40 | + }, $text); | |
| 41 | + | |
| 42 | + // get rid of HTML tags | |
| 43 | + $text = strip_tags($text); | |
| 44 | + | |
| 45 | + // remove duplicate white spaces and replace new lines with spaces | |
| 46 | + $text = preg_replace("/(\s{2,})|(\R+)/", ' ', $text); | |
| 47 | + | |
| 48 | + // calculate total length of the text | |
| 49 | + $len = strlen($text); | |
| 50 | + | |
| 51 | + // Check whether we should take a substring of the text. | |
| 52 | + // Reserve an additional 25% of characters to avoid breaking the | |
| 53 | + // text too close to the end of the string. | |
| 54 | + if ($max && $len > $max * 1.25) { | |
| 55 | + // explode the string in words | |
| 56 | + $chunks = explode(' ', $text); | |
| 57 | + | |
| 58 | + $text = ''; | |
| 59 | + | |
| 60 | + // keep adding words until we reach the maximum threshold | |
| 61 | + while ($chunks && strlen($text) < $max) { | |
| 62 | + $text .= array_shift($chunks) . ' '; | |
| 63 | + } | |
| 64 | + | |
| 65 | + // get rid of trailing special characters and add the ellipsis | |
| 66 | + $text = rtrim($text, '.,?!;:#\'"([{ ') . '...'; | |
| 67 | + } | |
| 68 | + | |
| 69 | + return $text; | |
| 70 | + } | |
| 71 | + | |
| 72 | + /** | |
| 22 | 73 | * Calculates the maximum upload file size and returns string with unit or the size in bytes. |
| 23 | 74 | * |
| 24 | 75 | * @param bool $unitOutput This parameter determines whether the return value |
| 25 | 76 | * should be a string with a unit. |