Using PHP's substr() Function for String Manipulation

This article explains how to use PHP's substr() function to extract portions of a string, covering its syntax, parameters, and practical examples including specifying start positions, lengths, and negative offsets for flexible substring extraction.

php Courses
php Courses
php Courses
Using PHP's substr() Function for String Manipulation

In PHP, string handling is a common task, and the substr() function provides a convenient way to extract a part of a string.

The function signature is:

string substr ( string $string , int $start [, int $length ] )

Parameters: $string: the input string to be sliced. $start: the zero‑based position where extraction begins. $length (optional): the number of characters to extract; if omitted, extraction continues to the end of the string.

Examples:

Example 1: Extract a substring with specified length

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

This extracts the first five characters of the string.

Example 2: Extract without specifying length

$str = "Hello, World!";
$sub_str = substr($str, 7);
echo $sub_str; // outputs "World!"

Here the extraction starts at position 7 and continues to the end.

Example 3: Using a negative start offset

$str = "Hello, World!";
$sub_str = substr($str, -6, 5);
echo $sub_str; // outputs "World"

A negative start counts from the end of the string; this example extracts five characters starting six positions from the end.

The substr() function is flexible, but note that if $start exceeds the string length, an empty string is returned, and a negative $length is treated as zero.

By mastering substr(), developers can efficiently manipulate strings in PHP applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPStringTutorialsubstr
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

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.