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

It's just math

$sub = substr($str, 3, 5 - 3);

The length is the end minus the start.


function my_substr_function($str, $start, $end)
{
  return substr($str, $start, $end - $start);
}

If you need to have it multibyte safe (i.e. for chinese characters, ...) use the mb_substr function:

function my_substr_function($str, $start, $end)
{
  return mb_substr($str, $start, $end - $start);
}

Just subtract the start index from the end index and you have the length the function wants.

$start_index = 3;
$end_index = 5;
$sub = substr($str, $start_index, $end_index - $start_index);