substr
Returns part of a string, counting in bytes.
Syntax
substr(string $string, int $offset, ?int $length = null): stringParameters
| Parameter | Type | Description |
|---|---|---|
| $string | string | The source string. |
| $offset | int | The start position, counting from zero. A negative value counts from the end. |
| $length | ?int | Optional. How many bytes to take; to the end of the string by default. |
Return value
stringThe selected part of the string.
Examples
The first characters and the tail of a string:
<?php
echo substr('programming', 0, 7), "\n";
echo substr('programming', -4);Output:
program
mingA file extension:
<?php
$file = 'photo.jpeg';
echo substr($file, strrpos($file, '.') + 1);Output:
jpegNotes
The function counts bytes, so it cuts non-ASCII letters in half. Use mb_substr() for text in any language.
See also
In the tutorial
- Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.