Substring problem

how do I tell PHP to substring a string from a given position in the string to another given position in the string (like you can in Java - )?

in PHP that 3rd, optional param to method substr() can ONLY be the LENGTH of the substring?
http://php.net/manual/en/function.substr.php

and if you don’t know what the length of the substring will be? I don’t get this…

here’s example of string I need to parse:

/photos/section6/page8/photos.php

how do I isolate from 2nd slash to 3rd slash and from 3rd slash to 4th slash?

(i.e., I need to extract “section6” and “page8”
(and “section6” can also be “section12” and “page8” can also be “page11”…))

$posOfSlash1 = strpos($URI, ‘/’, 5);
$posOfSlash2 = strpos($URI, ‘/’, 14);

you can’t do the following in PHP???
$_currSect = substr($URI, $posOfSlash1,$posOfSlash2);
that 3rd param can only be length of substring returned?

I don’t believe this…:frowning:

(I love the ‘offset’ param though, in method strpos()…:wink:

thank you…

Yes, it must be the length, so your third parameter would be

$posOfSlash2 - $posOfSlash1

$_currSect = substr($URI, $posOfSlash1,$posOfSlash2 - $posOfSlash1);

You could also use explode, which imho is more readable here

$url = '/photos/section6/page8/photos.php';
$parts = explode('/', $url); // ['', 'photos', 'section6', 'page8', 'photos.php']
$section = $parts[2];
$page = $parts[3];
2 Likes

thank you very much… that “explode” fn is very handy… (returns an array, unlike Java StringTokenizer… no “explode” fn in Java…:wink: