SyntaxStudy
Sign Up
Home PHP Reference substr()

substr()

function

Returns part of a string, starting at offset for the given length. Negative offset counts from the end.

Syntax

substr(string $string, int $offset, ?int $length = null): string

Example

php
<?php
$str = 'Hello World';
echo substr($str, 6);      // 'World'
echo substr($str, 6, 3);   // 'Wor'
echo substr($str, -5);     // 'World'

function truncate(string $s, int $n): string {
    return strlen($s) > $n ? substr($s, 0, $n).'...' : $s;
}