Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP substr() function

Reference for PHP substr(): extract part of a string by start and length, negative arguments, empty-string results in PHP 8 and multibyte pitfalls.

substr() returns a portion of a string, chosen by a start position and an optional length. It is one of the most used string functions: cutting off prefixes, taking the first N characters, getting a file extension, or the last few digits of a number.

Both arguments can be negative to count from the end. In PHP 8.0 and later the function always returns a string (an empty string when nothing is selected) rather than false.

PHP
<?php
echo substr("Hello, world", 7);       // world
echo substr("Hello, world", 0, 5);    // Hello
echo substr("Hello, world", -5, 3);   // wor

Try it

PHP Start and length

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Common uses and the multibyte trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
substr(string $string, int $offset, ?int $length = null): string
Name Description
$string The input string.
$offset Where the part starts. Positive: from the beginning (0 is the first byte). Negative: from the end. A negative offset beyond the start is treated as 0.
$length Optional. Positive: maximum number of bytes to return. Negative: that many bytes are left off the end. null or omitted: to the end of the string.

Return value: the extracted part, or an empty string if $offset is beyond the end or the length selects nothing.

Usage notes

  • PHP 8.0 change. Before 8.0, substr() returned false when the offset was past the end. Now it returns "", so code that tested for false needs updating.
  • null length (PHP 8.0+) means "to the end". Older PHP versions did not accept null.
  • Bytes, not characters. On UTF-8 text use mb_substr(), otherwise you can split a multibyte character and produce invalid text.
  • Negative length removes characters from the end: substr("abcdef", 1, -1) is "bcde".
  • Position-based work is usually paired with strpos() to find where to cut.
  • Replace instead of extract with substr_replace().
  • Single character access is $s[0] or $s[-1], but those throw warnings or errors for out-of-range offsets, while substr() does not.
  • Efficient. It copies only the selected part, so slicing in a loop on a large string is fine, but copying a large tail over and over is not.