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.
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.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.