Truncate string to given maximum length without breaking words
This method can truncate between words, sentences, punctuation or blocks (like paragraphs).
See the type
option for details on how it should truncate. By default it truncates between
words. Description of types:
- word: truncate to closest word.
- punctuation: truncate to closest punctuation within sentence.
- sentence: truncate to closest sentence.
- block: truncate to closest block of text (like a paragraph or headline).
Note that if your specified type
is something other than “word”, and it cannot be matched
within the maxLength, then it will attempt a different type. For instance, if you specify
“sentence” as the type, and it cannot match a sentence, it will try to match to “punctuation”
instead. If it cannot match that, then it will attempt “word”.
HTML will be stripped from returned string. If you want to keep some tags use the keepTags
or keepFormatTags
options to specify what tags are allowed to remain. The keepFormatTags
option that, when true, will make it
retain all HTML inline text formatting tags.
Available since version 3.0.101.
Example
// Truncate string to closest word within 150 characters
$s = $sanitizer->truncate($str, 150);
// Truncate string to closest sentence within 300 characters
$s = $sanitizer->truncate($str, 300, 'sentence');
// Truncate with options
$s = $sanitizer->truncate($str, [
'type' => 'punctuation',
'maxLength' => 300,
'visible' => true,
'more' => '…'
]);
Usage
// basic usage
$string = $sanitizer->truncate(string $str);
// usage with all arguments
$string = $sanitizer->truncate(string $str, $maxLength = 300, $options = []);
Arguments
Name | Type(s) | Description |
---|---|---|
str | string | String to truncate |
maxLength (optional) | int, array | Maximum length of returned string, or specify $options array here. |
options (optional) | array, string | Options array, or specify
|
Return value
string
$sanitizer methods and properties
API reference based on ProcessWire core version 3.0.236