evilReiko
evilReiko

Reputation: 20483

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

$str = 'HelloWorld';
$sub = substr($str, 3, 5);
echo $sub; // prints "loWor"

I know that substr() takes the first parameter, 2nd parameter is start index, while 3rd parameter is substring length to extract. What I need is to extract substring by startIndex and endIndex. What I need is something like this:

$str = 'HelloWorld';
$sub = my_substr_function($str, 3, 5);
echo $sub; // prints "lo"

Is there a function that does that in php? Or can you help me with a workaround solution, please?

Upvotes: 55

Views: 72906

Answers (5)

Tim
Tim

Reputation: 3198

You can just use a negative value on the third parameter:

echo substr('HelloWorld', 3, -5);
// will print "lo"

If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative).

As stated at the substr documentation.

Upvotes: 4

Andreas
Andreas

Reputation: 2678

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);
}

Upvotes: 17

BlackBeltScripting
BlackBeltScripting

Reputation: 187

Not exactly...

If we have a start index as 0, and we want JUST the first char, it becomes difficult as this will not output what you want. So if your code is requiring an $end_index:

// We want just the first char only.
$start_index = 0;
$end_index = 0;
echo $str[$end_index - $start_index]; // One way... or...
if($end_index == 0) ++$end_index;
$sub = substr($str, $start_index, $end_index - $start_index);
echo $sub; // The other way.

Upvotes: 1

Dan Grossman
Dan Grossman

Reputation: 52372

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);

Upvotes: 10

KingCrunch
KingCrunch

Reputation: 132051

It's just math

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

The length is the end minus the start.

Upvotes: 92

Related Questions