Backend Development 4 min read

Using PHP substr Function to Extract Substrings

This article explains how to use PHP's built‑in substr function to retrieve substrings by specifying start positions and lengths, covering basic syntax, parameter details, return values, and common examples such as extracting the last characters, specific ranges, and converting substrings to uppercase.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP substr Function to Extract Substrings

In PHP programming, extracting parts of a string is common, and the built‑in substr function can be used for this purpose.

1. Basic usage of substr

The substr function retrieves a substring of a specified length from a string. Its syntax is:

substr(string $string, int $start, int $length): string

Parameters

$string : the input string.

$start : start position, index starts at 0.

$length : length of the substring; if omitted, goes to the end.

Return value

Returns the extracted substring.

Example:

$string = "Hello, World!";
$substring = substr($string, 0, 5); // from position 0, length 5
echo $substring; // outputs "Hello"

Other common usages:

2. Get the last characters

$string = "Hello, World!";
$substring = substr($string, -6); // last 6 characters
echo $substring; // outputs "World!"

Using a negative start index counts from the end of the string.

3. Get a range and convert to uppercase

$string = "Hello, World!";
$substring = strtoupper(substr($string, 7, 5)); // get substring and uppercase
echo $substring; // outputs "WORLD"

Notes:

The $start parameter can be negative.

If $start exceeds the string length, the result is empty.

If $length is zero or negative, the result is empty.

String indices start at 0.

In summary, the PHP substr function allows flexible substring extraction by specifying start position and length, enabling common string operations such as extracting ranges, the last characters, or converting parts to uppercase.

BackendPHPtutorialstring-manipulationsubstr
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.