Skip to content

Core\Str::slice

Returns a part of a string, chosen by its position.

Core\Str::slice takes a string, an offset and a length. The offset is where the part starts, and the first character is at offset 0. The length is how many characters the part has. Leave the length out, or give null, to take everything to the end.

A negative offset counts from the end, so -3 starts three characters before the end. A negative length stops that many characters before the end. An offset past the end gives an empty string, and no error is thrown.

Positions count characters as a person sees them, not bytes. "é" and a flag like 🇩🇪 are one character each, so a slice never cuts one in half.

Parameters

  • $sstringThe string to take the part from.
  • $offsetintWhere the part starts. The first character is at 0. A negative offset counts from the end.
  • $length?intdefault nullHow many characters to take. A negative length stops that many characters before the end. null takes everything to the end.

Return value

Returns string. The part as a new string. It is "" when the part is empty or the offset is past the end. $s does not change.

Examples

Offsets

<?nvs
// Shows how to take a part of a text by its position.
var $s = 'Hello, World!';
// Without a length, the part runs to the end. This prints `World!`.
echo Core\Str::slice($s, 7), "\n";
// The first five characters. This prints `Hello`.
echo Core\Str::slice($s, 0, 5), "\n";
// A negative offset counts from the end. This prints `World`.
echo Core\Str::slice($s, -6, 5), "\n";
Output
World!
Hello
World

Negative length

<?nvs
// Shows how a negative length and an offset past the end work.
var $file = 'report-2026.csv';
// A negative length stops that many characters before the end.
// This prints `report-2026`, without the last four characters.
echo Core\Str::slice($file, 0, -4), "\n";
// This prints `2026`, the four characters before `.csv`.
echo Core\Str::slice($file, -8, 4), "\n";
// An offset past the end gives an empty string. No error is thrown.
echo '[', Core\Str::slice($file, 50), "]\n";
Output
report-2026
2026
[]

Shorten a title

<?nvs
// Shortens long titles for a list, and adds "…" to each title that was cut.
class Preview
{
public static function shorten(string $title, int $max): string
{
if (Core\Str::length($title) <= $max) {
return $title;
}
// Takes the first `$max - 1` characters, so the result with "…" has `$max` characters.
return Core\Str::slice($title, 0, $max - 1) . '…';
}
}
array<string> $titles = ['Café opening hours', 'Größenwahn: a short history of big plans', 'News'];
// "é" and "ö" count as one character each, so no character is cut in half.
foreach ($titles as string $title) {
echo Preview::shorten($title, 16), "\n";
}
Output
Café opening ho…
Größenwahn: a s…
News