Mastering PHP substr(): How to Extract Substrings Effectively

This article explains the PHP substr() function, detailing its signature, parameter behavior for positive and negative start and length values, return values, and provides multiple code examples demonstrating various edge cases and expected outputs.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Mastering PHP substr(): How to Extract Substrings Effectively

Function Overview

The substr() function returns a portion of a string, defined by a start position and an optional length.

Signature

string substr (string $string, int $start [, int $length])

Parameters $string (string): The input string. $start (int): If non‑negative, the extraction starts at that position counted from 0; if negative, counting starts from the end of the string. $length (int, optional): Determines how many characters to include. Positive values limit the result to that many characters from $start. Negative values omit that many characters from the end. Zero, FALSE or NULL produce an empty string. If omitted, the substring runs to the end of $string.

Return Value

On success, the extracted substring is returned. If the start position exceeds the string length or an error occurs, FALSE is returned.

Examples

<?php
echo "1) " . var_export(substr("pear", 0, 2), true) . PHP_EOL;
echo "2) " . var_export(substr(54321, 0, 2), true) . PHP_EOL;
echo "3) " . var_export(substr(new apple(), 0, 2), true) . PHP_EOL;
echo "4) " . var_export(substr(true, 0, 1), true) . PHP_EOL;
echo "5) " . var_export(substr(false, 0, 1), true) . PHP_EOL;
echo "6) " . var_export(substr("", 0, 1), true) . PHP_EOL;
echo "7) " . var_export(substr(1.2e3, 0, 4), true) . PHP_EOL;
?>

Output:

1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) false
6) false
7) '1200'
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPTutorialString Manipulationsubstr
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.