evilReiko evilReiko - 4 years ago 145
PHP Question

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?

Answer Source

It's just math

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

The length is the end minus the start.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download