PHP 8 reference · String Functions

PHP substr() Function

Return part of a string, given a start position and an optional length. Negative values count from the end.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
string The input string.
offset Start position from 0; negative counts back from the end.
length optional How many bytes to take; negative leaves that many off the end; null takes the rest.

Return value

The extracted part, or "" when the offset is past the end.

Examples

Take part of a stringTry it yourself
<?php
$text = "ReadyCamel";
echo substr($text, 0, 5), "\n";
echo substr($text, 5), "\n";
echo substr($text, -5, 3), "\n";

Output

Ready
Camel
Cam
Ends of a stringTry it yourself
<?php
$file = "invoice-2026.pdf";
echo substr($file, -3), "\n";   // extension
echo substr($file, 0, -4), "\n"; // drop it

Output

pdf
invoice-2026
Past the endTry it yourself
<?php
var_dump(substr("abc", 10));

Output

string(0) ""

Common mistakes

  • Positions are bytes: substr("café", 0, 4) cuts é in half. Use mb_substr() for UTF-8 text.
  • To get a file's extension, pathinfo($file, PATHINFO_EXTENSION) handles names without a dot.

Version history

VersionChange
PHP 4.0Added
PHP 8.0Returns an empty string instead of false when the offset is past the end.

In other languages

Was this page helpful?