PHP substr(): Extract a String by Offset and Length

PHP substr() extracts part of a string from a byte offset. The first byte is at offset 0. To slice valid UTF-8 text by characters, use mb_substr().

How offset and length work

The official PHP substr() reference calls the parameters substr($string, $offset, $length). The length is optional. Offsets and lengths refer to bytes in the PHP string.

A positive offset skips bytes from the start. A negative offset counts back from the end. For example, offset -3 in abcdefg starts at e.

A positive length gives the maximum bytes to take. An omitted or null length in PHP 8 takes the rest of the string. A length of 0 yields an empty string.

Run the examples and check the output

Save this as example.php and run php example.php. var_export() adds quotes to the display, so an empty result is visible.

<?php
$value = 'abcdefg';
$parts = [
    substr($value, 3),
    substr($value, 3, 2),
    substr($value, 3, 1),
    substr($value, 3, -1),
    substr($value, 3, -2),
    substr($value, -3),
    substr($value, -3, 2),
    substr($value, -3, 1),
    substr($value, -3, -1),
    substr($value, -3, -2),
    substr($value, 3, null),
    substr($value, 3, 0),
    substr($value, 8),
];

foreach ($parts as $part) {
    echo var_export($part, true), PHP_EOL;
}
Call Return value
substr($value, 3) 'defg'
substr($value, 3, 2) 'de'
substr($value, 3, 1) 'd'
substr($value, 3, -1) 'def'
substr($value, 3, -2) 'de'
substr($value, -3) 'efg'
substr($value, -3, 2) 'ef'
substr($value, -3, 1) 'e'
substr($value, -3, -1) 'ef'
substr($value, -3, -2) 'e'
substr($value, 3, null) 'defg'
substr($value, 3, 0) ''
substr($value, 8) ''

In PHP 8, a positive offset beyond the end returns an empty string ''. Older PHP versions returned false for some invalid ranges. Use $part === '' to check an empty result in PHP 8.

Distinguish negative offset from negative length

substr($value, -3, -1) starts at e and leaves off the last byte, yielding ef. Negative length defines how many bytes to omit at the end of the original string.

Extract a known fixed-width suffix

If your filename format guarantees a four-byte suffix such as .pdf, this prints .pdf. Use a delimiter-based approach when the suffix width varies.

<?php
$filename = 'invoice-2026.pdf';
echo substr($filename, -4), PHP_EOL;

Slice UTF-8 by character

The byte representation of PHP strings lets substr() cut inside a UTF-8 character. With the mbstring extension, pass 'UTF-8' to mb_substr() to count characters. Run php -m to check that the extension is loaded.

<?php
$text = "A\u{00E9}B";
echo bin2hex(substr($text, 1, 1)), PHP_EOL;
echo mb_substr($text, 1, 1, 'UTF-8'), PHP_EOL;

The first line, c3, shows the first byte of the two-byte character é. The second line prints é intact.

For user-perceived characters such as a base letter with a combining mark or a multi-code-point emoji, use grapheme_substr() from the intl extension.