From e66834b5a67800970469349649e9519c319ab769 Mon Sep 17 00:00:00 2001 From: Hakim Zulkufli Date: Sun, 6 Aug 2017 22:17:34 +0800 Subject: [PATCH] A new function is created to achieve this, Text::truncate which is based on Text::cut from the text.class.php helper. Limit is set to 60 characters. Example A: Content has over 60 characters. Title = First 60 characters + remaining characters of the last word + '...' Example B: Content has less than or equal to 60 characters Title = All. Example C: Content only has one word but is over 60 characters. Title = First 60 characters + '...' Why B and C differ from each other? Because we do not want the whole that one weird word with over 60 characters to make its way to the title. It's probably unrealistic, the code can be much cleaner with B and C combined. Feel free to discuss. --- bl-kernel/dbpages.class.php | 15 ++++++++++++++- bl-kernel/helpers/text.class.php | 26 ++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/bl-kernel/dbpages.class.php b/bl-kernel/dbpages.class.php index 2018f3c5..73c04db4 100644 --- a/bl-kernel/dbpages.class.php +++ b/bl-kernel/dbpages.class.php @@ -31,7 +31,20 @@ class dbPages extends dbJSON { $dataForDb = array(); // This data will be saved in the database $dataForFile = array(); // This data will be saved in the file - + + // Generate title if empty + if( empty($args['title']) ) { + $args['title'] = Text::truncate($args['content'], 60); + + // Assign the new title to the slug as well. + $args['slug'] = $args['title']; + } + + // Generate description if empty + if( empty($args['description']) ) { + $args['description'] = Text::truncate($args['content'], 100); + } + // Generate key $key = $this->generateKey($args['slug'], $args['parent']); diff --git a/bl-kernel/helpers/text.class.php b/bl-kernel/helpers/text.class.php index 9955ca2c..6fba3855 100644 --- a/bl-kernel/helpers/text.class.php +++ b/bl-kernel/helpers/text.class.php @@ -227,4 +227,30 @@ class Text { create_function('$input', 'return "
".htmlentities($input[2])."
";'), $string); } + + // Truncates the string under the limit specified by the limit parameter. + public static function truncate($string, $limit, $end = '...') + { + // Check if over $limit + if(mb_strlen($string) > $limit) { + + // Check if string is only one word + if(preg_match('/\s/', $string)) { + + // Append the string specified by the end parameter to the end of the string as it is over the limit. + $truncate = trim(mb_substr($string, 0, mb_strpos($string, ' ', $limit, 'UTF-8'), 'UTF-8')); + } else { + $truncate = trim(mb_substr($string, 0, $limit, 'UTF-8')); + } + $truncate = $truncate.$end; + } else { + $truncate = $string; + } + + if(empty($truncate)) { + return ''; + } + + return $truncate; + } } \ No newline at end of file