{substr:string:start:length:add}

Description

Returns part of a string. Give it the input text, a start position (0-based; a negative value counts back from the end), an optional length (a negative length cuts that many characters off the end instead), and an optional add string. The add string is appended only when the result is actually shorter than the input - which makes this the standard way to shorten a headline or teaser and show an ellipsis. Counts characters in a UTF-8 aware way, not bytes. With no length the rest of the string is returned.

Parameters

string required

The input text to take characters from. Counts characters in a UTF-8 aware way (a multi-byte character is one position, not several bytes).

start required default 0

The position to start at, counting from 0 (so 0 is the first character). A negative value counts back from the end: -3 starts three characters before the end.

length optional default 999999999 (the whole remainder)

How many characters to take. If omitted, the rest of the string from start is returned. A negative length keeps everything except that many characters cut off the end.

add optional default (empty)

A string appended to the result, but only when the result is actually shorter than the input. Set it to ... to get an ellipsis on truncated text; leave it empty for a plain cut.

Examples

test{substr:Hello World:0:5}
ExpectedHello
ActualHello
Take characters from position 0 with length 5.
test{substr:Hello World:6}
ExpectedWorld
ActualWorld
Give only a start and the rest of the string is returned. Length defaults to the whole remainder. Position 6 is the W of World.
test{substr:The quick brown fox:0:9:...}
ExpectedThe quick...
ActualThe quick...
The fourth parameter (add) is appended only when the text was actually cut. This is the standard headline/teaser truncation pattern.
test{substr:Hello:0:50:...}
ExpectedHello
ActualHello
Because the requested length (50) is longer than the string, nothing is removed, so the add string (...) is NOT appended. Safe for variable-length text.
test{substr:report.pdf:-3}
Expectedpdf
Actualpdf
A negative start position counts back from the end of the string. -3 returns the last three characters - handy for file extensions.
test{substr:report.pdf:0:-4}
Expectedreport
Actualreport
A negative length drops that many characters off the end instead of keeping a count. -4 removes the trailing .pdf, leaving the base name.