Re: Negative string offsets

From: Date: Thu, 17 Apr 2014 22:11:09 +0000
Subject: Re: Negative string offsets
References: 1 2 3 4 5  Groups: php.internals 
Request: Send a blank email to internals+get-73733@lists.php.net to get a copy of this message
Hi, On Thu, Apr 17, 2014 at 11:22 PM, Andrey Andreev <narf@devilix.net> wrote: > Hi, > > On Thu, Apr 17, 2014 at 6:07 PM, Johannes Schlüter > <johannes@schlueters.de> wrote: > > On Thu, 2014-04-17 at 17:18 +0300, Andrey Andreev wrote: > >> For example, every time you need to check for a filename extension, > >> last segment of a path, etc. When I need that, I always endup with > >> substr(), strrchr() or explode(), end() ... both are suboptimal. > > > > I don't see where this helps in that case. > > > > $sep = strrpos($filename, "."); > > if ($sep !== false) { > > $ext = substr($filename, $sep + 1); > > } > > > > is clear and concise, two fcalls, can be understood even after years and > > the new programmer easily. > > > > This is the most concise form I came up using this new offset: > > > > $ext = ''; > > $pos = -1; > > do { > > $ext = $filename[$pos].$ext; > > } while ($filename[--$pos] != '.'); > > > > While this form is bugged as it assumes that there is a . without > > checking. For checking I'd have to use strlen(), but if i call strlen() > > I can also initialize $pos accordingly and iterate from strlen() to 0. > > Also this form does more comparisons and way more allocations and is (in > > my opinion) way harder to understand. > > > > Maye I didn't see a simple form ... > > > > johannes > > For most filename extensions: > > if ($filename[-4] === '.') > { > $ext = substr($filename, -3); > } > I know that this was just an example of the use-case, but to get a file extension you would typically do: $ext = pathinfo($filename, PATHINFO_EXTENSION); ;-) > Or, checking if a path has a slash at the end: > > if ($path[-1] === '/') { ... } > > I'm talking strictly about validation here (and yes, the filename > example won't work with i.e. .jpeg, but would satisfy a large amount > of use cases), comparing stuff on the fly. > > Cheers, > Andrey. > > -- > PHP Internals - PHP Runtime Development Mailing List > To unsubscribe, visit: http://www.php.net/unsub.php > > -- -- Tjerk

« previous php.internals (#73733) next »