Current Location: Home> Latest Articles> Comprehensive Guide to PHP substr(): Efficiently Extract Substrings

Comprehensive Guide to PHP substr(): Efficiently Extract Substrings

M66 2025-06-15

Introduction to PHP Function substr(): Extracting Part of a String

In PHP development, string manipulation is a very common task. When you need to extract specific content from a string, PHP offers a very useful function — substr().

The substr() function is used to extract a portion of a string. Its basic syntax is as follows:

<span class="fun">string substr(string $string, int $start [, int $length])</span>

Parameter explanations:

  • $string: The string to extract from.
  • $start: The starting position of extraction, with the index starting at 0.
  • $length: Optional. Specifies the length of the extracted substring. If omitted, substr() extracts from the start position to the end of the string.

Below are several examples to help understand how to use substr().

Example 1: Extracting a Portion of a String

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

In this example, we extract 5 characters from the beginning of $str and assign it to $sub_str. The output is "Hello".

Example 2: Extracting From a Specific Position to the End (Without Specifying Length)

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

This example extracts the substring starting from the 7th character to the end of the string, resulting in "World!".

Example 3: Using Negative Parameters to Extract a String

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

Here, a negative start position counts from the end of the string. Starting from the 6th character from the end, we extract 5 characters, resulting in "World".

Note that if $start exceeds the string length, the returned substring will be empty. If $length is negative, it will be treated as zero. Negative parameters allow flexible extraction from the end of the string.

Summary

The substr() function is a very practical and commonly used tool in PHP string processing. By flexibly using the $start and $length parameters, you can easily extract any required substring. Mastering this function greatly facilitates daily PHP string operations.