strings
strings copied to clipboard
Formatter feature request (text limit / word wrap)
I do not have concept to implement this thing, but I think that it can be extension to asText formatter method.
First, there are a few methods of word wrapping:
- Strict (as much as possible characters, can break the word)
- Word rounded up (include last word that reach the limit)
- Word rounded down (include last word before reach the limit)
I want use word wrapping to limit text.
I know that I should use substr
, but this method will break last word.
There is also wordwrap
, but first it does have third wrapping method, and secondly it only insert break line character.
This feature can be used in:
- DataGrid columns and DetailView to display first few words of content,
- Headers on page and page title, when it use some field that can be too long. (For example "question content" on "question update page",
https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseStringHelper.php
Thanks @lynicidn, but none method form this class cover my case.
I used truncate
for now, but it break last word.
show how you use it
Example:
$this->title = Yii::t('app', 'Update: {question}', [
'question' => StringHelper::truncate($model->question, 20)
]);
In question is string: Do you like drink coffee at work?
Function return string: Update: Do you like drink co...
I expect string: Update: Do you like drink...
https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseStringHelper.php#L128
@lynicidn I do not know how many words should be printed. It depends on word lengths.
@mklemarczyk ok, you right - i don't help for you - sorry.
simple way use truncate + find "white space of end" and apply endWith ('white space + partword + ...')
Here is what you need. strrpos with negative limit finds last space in string before the limit.
function truncate($string, $limit)
{
return substr($string, 0, strrpos($string, ' ', $limit - strlen($string)));
}
echo truncate('Do you like drink coffee at work?', 20);
Output is 'Do you like drink'
StringHelper::truncateWords() is available since Yii 2.0.1
as far as I understood the request it was to truncate words based on a maximum string length. StringHelper::truncateWords() is based on word count.