The substr()
function in PHP is used to extract a portion of a string. It returns a part of the original string, starting from a specified position (and optionally, with a specified length).
Syntax:
substr(string $string, int $start, int $length = null): string
- $string: The input string.
- $start: The starting position. If it's positive, the function will start from the beginning. If it's negative, it will start from the end of the string.
- $length (optional): The number of characters to extract. If omitted, the function will extract the rest of the string from the starting position. If it's negative, it will exclude that many characters from the end.
Examples:
1. Basic Example (Extracting from a specific position):
$str = "Hello, World!";
echo substr($str, 7); // Outputs: World!
- Here, it starts at index 7 (the "W" in "World") and extracts the rest of the string.
2. Specifying Length:
$str = "Hello, World!";
echo substr($str, 0, 5); // Outputs: Hello
- It starts at index 0 (the "H") and extracts 5 characters ("Hello").
3. Negative Start Index (Counting from the end):
$str = "Hello, World!";
echo substr($str, -6); // Outputs: World!
- The negative index
-6
means "count from the end of the string," so it starts from the "W" of "World."
4. Negative Length:
$str = "Hello, World!";
echo substr($str, 0, -1); // Outputs: Hello, World
- The negative length
-1
means "exclude the last character," so it removes the "!" at the end.
5. Using substr()
with Negative Start and Length:
$str = "Hello, World!";
echo substr($str, -6, 3); // Outputs: Wor
- It starts from the 6th character from the end and extracts 3 characters.
Edge Cases:
- If the
$start
exceeds the string length,substr()
will return an empty string. - If
$start
is negative and its absolute value is greater than the string length, it will be treated as the string's starting position.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.