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.
This commit is contained in:
Hakim Zulkufli 2017-08-06 22:17:34 +08:00
parent dd06fb5a8a
commit e66834b5a6
2 changed files with 40 additions and 1 deletions

View File

@ -32,6 +32,19 @@ 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']);

View File

@ -227,4 +227,30 @@ class Text {
create_function('$input', 'return "<pre><code $input[1]>".htmlentities($input[2])."</code></pre>";'),
$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;
}
}