← Back to Chapters

PHP substr() Function

? PHP substr() Function

? Quick Overview

The substr() function in PHP is used to extract a portion of a string. This function is often useful when you need to work with a substring within a larger string, such as extracting a part of a sentence or retrieving a fixed number of characters.

? Key Concepts

  • Works with zero-based indexing
  • Supports positive and negative positions
  • Can extract partial strings efficiently

? Syntax / Theory

? View Code Example
// Syntax of PHP substr() function
substr($string, $start, $length);
  • $string: The input string.
  • $start: The starting position (0-based index). Negative values start from the end.
  • $length: Number of characters to extract. Negative values exclude characters from the end.

? Example 1: Basic Usage

? View Code Example
// Extract substring starting from index 6
<?php
$string = "Hello World";
$substring = substr($string, 6);
echo $substring;
?>

? Output

World

? Example 2: Specifying Length

? View Code Example
// Extract first 5 characters from string
<?php
$string = "Hello World";
$substring = substr($string, 0, 5);
echo $substring;
?>

? Example 3: Using Negative Start Position

? View Code Example
// Extract last 5 characters using negative index
<?php
$string = "Hello World";
$substring = substr($string, -5);
echo $substring;
?>

? Example 4: Using Negative Length

? View Code Example
// Exclude last 6 characters from the string
<?php
$string = "Hello World";
$substring = substr($string, 0, -6);
echo $substring;
?>

? Interactive Example (Conceptual)

Imagine a text editor that highlights only a specific portion of a sentence. PHP internally performs the same operation using substr() to isolate characters before processing or displaying them.

? Use Cases

  • Extract usernames from emails
  • Trim strings for previews or summaries
  • Process fixed-length data inputs
  • Mask sensitive information

✅ Tips & Best Practices

  • Use negative values wisely to count from the end
  • Check string length before extracting substrings
  • For Unicode strings, prefer mb_substr()

? Try It Yourself

  • Extract the first 3 characters from a word
  • Display only the last 4 digits of a phone number
  • Build a function to shorten long strings dynamically