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

Comprehensive Guide to PHP substr() Function: Efficiently Extract Substrings

M66 2025-06-15

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

In PHP development, string manipulation is a very common task. Sometimes, we need to extract a portion of a string for further processing. PHP offers a very useful function called substr() specifically designed for this purpose.

Basic Usage of substr() Function

The substr() function extracts a part of a string. The function prototype is:

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

Parameter explanation:

  • $string: The string to be operated on.
  • $start: The starting position for extraction, zero-based index.
  • $length (optional): The length of the substring to extract. If not specified, substr() extracts from $start to the end of the string.

Example Demonstrations

Example 1: Extracting the first 5 characters

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

The above code extracts the first five characters from the string, resulting in "Hello".

Example 2: Extracting from a specified position without length

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

Here, extraction starts from the 7th character to the end of the string, outputting "World!".

Example 3: Using negative numbers as parameters

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

A negative $start means counting from the end of the string. This example extracts 5 characters starting from the 6th last character, resulting in "World".

Important Notes

  • If $start exceeds the string length, an empty string is returned.
  • If $length is negative, it is treated as 0, and an empty string is returned.
  • Negative parameters allow substring extraction starting from the end of the string.

Summary

The substr() function is an essential and practical tool for string manipulation in PHP. By using the $start and $length parameters flexibly, you can easily extract any part of a string. Mastering this function will make string operations more efficient and concise.