Current Location: Home> Latest Articles> Comprehensive Guide to PHP substr() Function: Practical Usage and Code Examples

Comprehensive Guide to PHP substr() Function: Practical Usage and Code Examples

gitbox 2025-08-02

What is the substr() Function

The substr() function in PHP is used to extract a portion of a string. It requires three parameters: the original string, the starting position, and the length of the substring, and returns the extracted substring.

Syntax of substr() Function

<span class="fun">substr(string $string, int $start, int|null $length = null): string</span>

Parameter explanation:

string: Required, the string to be processed.

start: Required, the starting position of the substring. A positive number counts from the beginning of the string, while a negative number counts from the end.

length: Optional, the length of the substring to extract. If omitted, it returns all characters from the start position to the end of the string.

Example Usage of substr() Function

$str = "Hello, World!";
$subStr = substr($str, 0, 5);
echo $subStr;  // Outputs "Hello"

In this example, we extract 5 characters starting from position 0 of the string $str, resulting in "Hello".

Return Value of substr() Function

The function returns a substring extracted from the original string according to the specified parameters.

Important Notes for substr() Function

If the start position is negative, substr() counts from the end of the string. For example:

$str = "Hello, World!";
$subStr = substr($str, -6);
echo $subStr;  // Outputs "World!"

If the start position exceeds the length of the string, an empty string is returned:

$str = "Hello, World!";
$subStr = substr($str, 20);
echo $subStr;  // Outputs ""

Common Use Cases for substr() Function

substr() is widely used in practice for tasks such as extracting file extensions, truncating parts of URLs, and more. For example, to get a file extension:

$fileName = "example.txt";
$extension = substr($fileName, strrpos($fileName, '.') + 1);
echo $extension;  // Outputs "txt"

In this example, strrpos() finds the last dot in the filename, and substr() extracts the extension starting right after that.

Summary

substr() is a frequently used PHP function for string manipulation that allows flexible extraction of substrings. Be mindful of how the start position and length parameters work, especially when using negative start positions or when the start exceeds the string length. For multibyte character strings, consider using mb_substr() to correctly handle characters beyond single bytes.