Re: Negative string offsets
| From: | Rasmus Lerdorf | Date: | Thu, 17 Apr 2014 15:25:34 +0000 |
| Subject: | Re: Negative string offsets | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-73723@lists.php.net to get a copy of this message | ||
On 04/17/2014 08:07 AM, Johannes Schlüter 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 ...
Yeah, it wouldn't make any sense unless it supported ranges. Something like:
if($filename[-4,4] === '.ext') ...
although, I don't see how that is better than:
if(substr($filename,-4) === '.ext') ...
The latter is much clearer.
-Rasmus