Re: Negative string offsets
| From: | Johannes Schlüter | Date: | Thu, 17 Apr 2014 15:07:34 +0000 |
| Subject: | Re: Negative string offsets | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-73721@lists.php.net to get a copy of this message | ||
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