How to extract substring by start-index and end-index?

How to extract substring by start-index and end-index?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Extracting Substrings by Start and End Indices in PHP

The native substr() function operates on a length basis, which is standard for string manipulation but often misaligned with how developers think about data boundaries. In your example, passing 3 as the second argument correctly sets the start index at 'l', but the third argument of 5 tells the engine to grab five characters total, resulting in "loWor". To extract a substring defined strictly by a starting point and an ending point—where the end index is inclusive—you cannot rely on a single built-in PHP function. You must derive the length programmatically before calling substr().

The logic is straightforward: calculate the difference between your end index and start index, then add one to include the character at the end index itself. The formula for the length becomes $endIndex - $startIndex + 1. Applying this to your specific case where you want characters starting at index 3 ('l') and ending at index 5 ('W'), the calculation is 5 - 3 + 1, which equals 3. Passing 3 as the length parameter to substr() yields the expected result of "loW".

$str = 'HelloWorld';
$startIndex = 3;
$endIndex = 5;

// Calculate length based on inclusive end index
$length = $endIndex - $startIndex + 1;

$sub = substr($str, $startIndex, $length);
echo $sub; // prints "loW"

While this requires a small amount of arithmetic, it is the most efficient approach in pure PHP because it avoids creating intermediate variables or relying on less optimized string functions. The overhead of performing simple integer subtraction and addition is negligible compared to the cost of parsing string data structures.

If you prefer a cleaner syntax that visually resembles the desired my_substr_function, you can create a closure or a helper function. This encapsulates the logic and makes the intent clearer in larger codebases. Here is how you might define such a utility:

function substrByRange(string $str, int $startIndex, int $endIndex): string {
    return substr($str, $startIndex, ($endIndex - $startIndex) + 1);
}

$sub = substrByRange('HelloWorld', 3, 5);
echo $sub; // prints "loW"

There are important edge cases to consider when implementing this. First, ensure that the $startIndex is valid. If you attempt to start at a negative number or beyond the string length, substr() will throw a warning in older PHP versions or silently return an empty string in newer versions, depending on context. Always validate inputs if this function is part of public-facing logic.

Second, handle scenarios where $endIndex is less than $startIndex. In your formula, this would result in a length of zero or negative. substr() handles a negative length gracefully by returning an empty string, but it is often better to throw an exception or return null explicitly to indicate invalid range parameters. This prevents silent failures that can be difficult to debug later.

For developers working within the Laravel ecosystem, similar logic exists in the collection helpers, though those operate on arrays rather than raw strings. However, understanding this native PHP behavior remains crucial when dealing with database query results or file contents where collections might not be applicable. If you are maintaining a legacy codebase using older PHP versions, be aware that substr() with invalid offsets used to trigger warnings more aggressively; modern PHP versions are more lenient but require explicit error handling for production robustness.

Ultimately, there is no magical built-in function that accepts start and end indices directly because the underlying C implementation of string functions historically optimized for length-based operations. Calculating the length on the fly ensures maximum compatibility and performance across all PHP environments without needing external dependencies or complex regex patterns.

Our network