How to Extract a Substring in PHP Using substr()

This article provides a quick guide on how to extract a specific portion of a string in PHP using the built-in substr() function. You will learn the anatomy of the function’s syntax, how to handle positive and negative offsets, and see clear code examples that you can immediately apply to your web development projects.

PHP substr() Syntax

The substr() function returns the part of a string specified by the start and length parameters.

substr(string $string, int $offset, ?int $length = null): string

Practical Examples

1. Basic Extraction (Using a Positive Offset)

To extract a substring starting from a specific position to the end of the string, provide only the string and a positive offset.

<?php
$text = "Welcome to PHP programming";

// Extract starting from index 11 (the 12th character) to the end
$result = substr($text, 11);

echo $result; // Outputs: PHP programming
?>

2. Extracting with a Specific Length

To get a precise number of characters, provide a positive integer as the third argument.

<?php
$text = "Welcome to PHP programming";

// Start at index 11 and extract exactly 3 characters
$result = substr($text, 11, 3);

echo $result; // Outputs: PHP
?>

3. Using a Negative Offset

A negative offset starts counting from the end of the string. An offset of -1 represents the last character, -2 the second to last, and so on.

<?php
$text = "Welcome to PHP programming";

// Extract the last 11 characters
$result = substr($text, -11);

echo $result; // Outputs: programming

4. Using a Negative Length

If you provide a negative length, the returned string will end that many characters from the end of the string.

<?php
$text = "Welcome to PHP programming";

// Start at index 11, and omit the last 4 characters ("ming")
$result = substr($text, 11, -4);

echo $result; // Outputs: PHP program