What does substr() do?
substr() extracts a portion of a string starting at $offset. A negative offset counts from the end of the string, and a negative length stops that many bytes before the end.
Syntax
substr(string $string, int $offset, ?int $length = null): string
Parameters
$string- The input string.$offset- Start position (0-based). Negative values count from the end:-1is the last byte.$length- Optional number of bytes to return. Omitted ornullmeans "to the end". A negative value leaves that many bytes off the end.
Return value
The extracted substring. Since PHP 8.0 it returns an empty string (instead of false) when $offset is past the end of the string.
substr() examples
Every example below shows the exact output it produces. Paste any of them into the editor above (or the online compiler) to run it.
1. Positive and negative offsets
<?php
$text = "Hello, World!";
echo substr($text, 0, 5) . "\n"; // first 5 characters
echo substr($text, 7) . "\n"; // from position 7 to the end
echo substr($text, -6) . "\n"; // last 6 characters
echo substr($text, -6, 5) . "\n"; // 5 characters, starting 6 from the end
echo substr($text, 0, -1) . "\n"; // everything except the last character
Output:
Hello World! World! World Hello, World
2. Truncate text with an ellipsis
<?php
function excerpt(string $text, int $max): string {
if (strlen($text) <= $max) {
return $text;
}
return rtrim(substr($text, 0, $max)) . "...";
}
echo excerpt("PHP is a popular general-purpose scripting language.", 20) . "\n";
echo excerpt("Short text", 20) . "\n";
Output:
PHP is a popular gen... Short text
3. Get a file extension and handle out-of-range offsets
<?php
$file = "report.final.pdf";
echo substr($file, strrpos($file, ".") + 1) . "\n";
var_dump(substr("abc", 5));
Output:
pdf string(0) ""
Common mistakes and gotchas
- Byte-based:
substr()can cut a UTF-8 character in half. Usemb_substr()for multibyte text. - PHP 7 vs PHP 8: code that checks
substr(...) === falseno longer works in PHP 8, where an out-of-range offset returns"". - File extensions:
pathinfo($file, PATHINFO_EXTENSION)is more robust thansubstr()+strrpos()for paths without a dot.