How to Use substr in PHP: Syntax and Examples
In PHP, use the
substr function to get a part of a string by specifying the string, the start position, and optionally the length. For example, substr('Hello', 1, 3) returns ell.Syntax
The substr function extracts a substring from a string.
- string: The original string you want to cut from.
- start: The position to start (0-based index). If negative, counts from the end.
- length (optional): How many characters to take. If omitted, takes till the end.
php
substr(string $string, int $start, ?int $length = null): string
Example
This example shows how to extract parts of a string using substr. It extracts 'ell' from 'Hello' and 'world' from 'Hello world'.
php
<?php $text = 'Hello world'; $part1 = substr($text, 1, 3); // starts at index 1, length 3 $part2 = substr($text, 6); // starts at index 6, till end echo $part1 . "\n"; echo $part2 . "\n"; ?>
Output
ell
world
Common Pitfalls
Common mistakes include:
- Using a start index larger than the string length returns an empty string.
- Negative length values are not allowed and cause unexpected results.
- Not handling multibyte (Unicode) strings properly;
substrworks byte-wise, so usemb_substrfor UTF-8 strings.
php
<?php // Wrong: start index too large echo substr('Hi', 5); // outputs empty string // Correct: check length before calling $start = 5; $text = 'Hi'; if ($start < strlen($text)) { echo substr($text, $start); } else { echo 'Start index too large'; } ?>
Output
Start index too large
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| string | The original string | 'Hello world' |
| start | Start position (0-based). Negative counts from end | 1 or -5 |
| length | Number of characters to extract (optional) | 3 or omitted |
Key Takeaways
Use substr(string, start, length) to extract parts of a string in PHP.
Start index is zero-based; negative start counts from the string end.
Omitting length extracts till the string's end.
substr works byte-wise; use mb_substr for multibyte strings.
Check start and length values to avoid empty or unexpected results.