substr() / mb_substr() Since: PHP 4(2000)
Extracts a portion of a string. For strings containing multibyte characters (such as Japanese), use mb_substr() to extract by character unit correctly.
Syntax
// Extracts a substring starting from the specified position. substr($string, $offset, $length); // Extracts a substring with multibyte character support. mb_substr($string, $start, $length, $encoding);
Functions
| Function | Description |
|---|---|
| substr($string, $offset, $length) | Extracts a substring by byte. $offset is the starting position, and $length (optional) is the number of characters to extract. |
| mb_substr($string, $start, $length, $encoding) | A multibyte-safe extraction function. Use this for strings that contain Japanese or other multibyte characters. |
Return Value
Returns the extracted substring. If $length is omitted, everything from the starting position to the end of the string is returned.
Sample Code
<?php
// Extracting from an ASCII string.
$str = "Hello World";
echo substr($str, 6); // Outputs "World" (from position 6 onward).
echo substr($str, 0, 5); // Outputs "Hello" (first 5 characters).
// Use mb_substr() for Japanese strings.
$address = "東京都渋谷区神南";
echo mb_substr($address, 0, 3, "UTF-8"); // Outputs "東京都".
echo mb_substr($address, 3, 3, "UTF-8"); // Outputs "渋谷区".
// A negative offset counts from the end of the string.
echo substr("Hello World", -5); // Outputs "World" (last 5 characters).
echo mb_substr("東京都渋谷区", -3, 3, "UTF-8"); // Outputs "渋谷区".
// A negative $length excludes that many characters from the end.
echo substr("Hello World", 0, -6); // Outputs "Hello" (excluding the last 6 characters).
// Example: extracting a file extension.
$filename = "report_2026.pdf";
$ext = substr($filename, strrpos($filename, ".") + 1);
echo $ext; // Outputs "pdf".
// Example: truncating a long string with an ellipsis.
$text = "This is a sample of a long sentence. It will be truncated after a certain number of characters.";
if (mb_strlen($text, "UTF-8") > 20) {
echo mb_substr($text, 0, 20, "UTF-8") . "..."; // Outputs "This is a sample of ...".
}
Overview
substr() extracts a portion of a string by specifying a starting position and length. You can also use negative values to count from the end of the string. For strings containing Japanese or other multibyte characters, using substr() will extract by byte, which can cause garbled text. Always use mb_substr() instead.
A negative starting position counts from the end of the string, and a negative length excludes that many characters from the end. If the length is omitted, everything from the starting position to the end of the string is returned.
To get the length of a string, use strlen() / mb_strlen(). To search within a string, use strpos(). To split a string, use explode().
If you find any errors or copyright issues, please contact us.