PHP substr() Function
The substr() function extracts a portion of a string starting at a specified position.
Syntax
substr(string $string, int $start, ?int $length = null): string
Parameters
| Parameter | Type | Description |
|---|---|---|
$string | string | The input string |
$start | int | Start position (0-based, negative from end) |
$length | int|null | Max characters to extract (optional) |
Return Value
Returns the extracted substring, or an empty string if start is beyond string length.
Try It Online
Output
Click Run to execute your code
More Examples
Get First N Characters
<?php
$str = "Hello World";
echo substr($str, 0, 5); // "Hello"
?>
Get Last N Characters
<?php
$str = "Hello World";
echo substr($str, -5); // "World"
?>
Remove Last N Characters
<?php
$str = "filename.txt";
echo substr($str, 0, -4); // "filename"
?>
Tip: For multibyte strings (UTF-8), use
mb_substr() instead.
Common Use Cases
- Extracting file extensions
- Truncating text for previews
- Parsing fixed-width data
- Getting parts of timestamps
Enjoying these tutorials?