PHP substr() Function: Usage, Parameters, and Examples
This article explains PHP's substr() function, detailing its signature, parameter meanings, behavior with positive and negative start and length values, edge cases, and provides multiple code examples demonstrating how to extract substrings under various conditions.
substr() returns a portion of a string.
Signature: string substr(string $string, int $start[, int $length])
Explanation: Returns the substring of $string defined by $start and $length . If $start is non‑negative, counting begins at that offset (0‑based). If negative, counting starts from the end of the string. If $length is omitted, the substring extends to the end of the string.
Parameter details:
string – the input string (must contain at least one character).
start – position where extraction begins. Positive values count from the start; negative values count backward from the end. If the string length is less than start , FALSE is returned.
length – optional. Positive values limit the number of characters returned. Negative values cause characters at the end of the string to be omitted. Zero, FALSE , or NULL results in an empty string. If omitted, extraction continues to the string's end.
Example 1:
<?php
$rest = substr("abcdef", -1); // returns "f"
$rest = substr("abcdef", -2); // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?>Example 2:
<?php
$rest = substr("abcdef", 0, 2); // returns "ab"
$rest = substr("abcdef", 2, 3); // returns "cde"
$rest = substr("abcdef", 4, -4); // returns "" (empty string)
?>Example 3 (character access):
<?php
$string = "abcdef";
echo $string[0]; // a
echo $string[3]; // d
echo $string[strlen($string) - 1]; // f
?>Example 4 (object to string conversion and var_export):
<?php
class apple {
public function __toString() { return "green"; }
}
echo "1) " . var_export(substr("pear", 0, 2, true), true) . PHP_EOL;
echo "2) " . var_export(substr(54321, 0, 2, true), true) . PHP_EOL;
echo "3) " . var_export(substr(new apple(), 0, 1, true), true) . PHP_EOL;
echo "4) " . var_export(substr(true, 0, 1, true), true) . PHP_EOL;
echo "5) " . var_export(substr(false, 0, 1, true), true) . PHP_EOL;
echo "6) " . var_export(substr("", 0, 1, true), true) . PHP_EOL;
echo "7) " . var_export(substr(1.2e3, 0, 4, true), true) . PHP_EOL;
?>The output of the above calls demonstrates how substr() behaves with strings, numbers, objects, booleans, empty strings, and scientific notation values.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.