tags:

views:

38

answers:

3

How can i extract the portion of a string giving the beginning and the end position?

I know there is a method called substr() but is not what im looking for (the third parameter is lenght of the portion..)

+1  A: 

If you have the start and end positions, the length is just end - start:

$string = "The quick brown fox jumped over the lazy dog";
$start = 4;
$end = 15;
substr($string, $start, $end - $start); //=> "quick brown"

See this in action at http://www.ideone.com/LRfYT.

Daniel Vandersluis
A: 

If you know the beginning and end locations, all you have to do is subtract to get the length of the part you want. Then go ahead and use substr().

Lord Torgamus
A: 

Th following will do what you want.

function ssubstr($string, $start, $end) {
    if ($end < 0) $length = strlen($string) + $end;
    else $length = $end - $start;
    return substr($string, $start, $length);
}

This method is safe for negative values of $end.

Note that it doesn't do any error checking

Jonathan Fingland