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
Syntax
substr(string $string, int $offset, ?int $length = null): string
Parameters
| Parameter | Description |
|---|---|
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
<?php
$text = "ReadyCamel";
echo substr($text, 0, 5), "\n";
echo substr($text, 5), "\n";
echo substr($text, -5, 3), "\n";
Output
Ready Camel Cam
<?php
$file = "invoice-2026.pdf";
echo substr($file, -3), "\n"; // extension
echo substr($file, 0, -4), "\n"; // drop it
Output
pdf invoice-2026
<?php
var_dump(substr("abc", 10));
Output
string(0) ""
Common mistakes
- Positions are bytes:
substr("café", 0, 4)cuts é in half. Usemb_substr()for UTF-8 text. - To get a file's extension,
pathinfo($file, PATHINFO_EXTENSION)handles names without a dot.
Version history
In other languages
slice()· Pythonstring.slice()· JavaScriptstring.substring()· JavaScript
Related
mb_substr()· Return part of a string by character position, so multibyte characters are never cut in half. The UTF-8 version of substr().substr_replace()· Replace part of a string, given a start position and length, with another string. Also inserts text or masks digits.strpos()· Find the position of the first occurrence of a substring. Returns false if it's not found, so compare with === false.str_split()· Split a string into an array of chunks of a given length, one byte each by default. Use mb_str_split() for UTF-8.- PHP Strings · tutorial