|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #54387 Add str_slice() function, simple & logical string slicing function
Submitted: 2011-03-26 10:19 UTC Modified: 2018-04-08 15:49 UTC
Avg. Score:4.4 ± 0.8
Reproduced:3 of 3 (100.0%)
Same Version:0 (0.0%)
Same OS:0 (0.0%)
From: birken at gmail dot com Assigned:
Status: Suspended Package: Strings related
PHP Version: 5.3SVN-2011-03-26 (SVN) OS: agnostic
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please — but make sure to vote on the bug!
Your email address:
Solve the problem:
30 + 42 = ?
Subscribe to this entry?

 [2011-03-26 10:19 UTC] birken at gmail dot com
The current state of string slicing in PHP is very confusing and non-obvious.

The substr() function attempted some nice string slicing features, but it just 
isn't a good interface for string slicing and due to legacy concerns it cannot 
be changed (I assume).

substr() problems:
- The interface is inconsistent and confusing.  When length is positive, then 
the function effectively returns from [start, start+length).  When length is 
negative, the function returns [start, str_len+length).  str_slice() has a much 
simpler interface: It returns from [start, end), and start and end may be 
defined as positive numbers from the start of the string or negative numbers 
from the end of the string.

- Returning FALSE when start + length parameters are invalid.  This is annoying 
because when using this function you always have to deal with this FALSE case if 
you need a string.  Here is an example where str_slice() produces a more logical 
output than substr:

print var_dump(substr('', -1) == '0'); // TRUE
print var_dump(str_slice('', -1) == '0'); // FALSE

This patch effectively solves the following bug as well: (substr should return '' instead of FALSE) (add str_startswith and str_endswith 
functions, which are trivial with str_slice, even in corner cases)

Test script:
Test is attached in the patch.


add-str_slice-function (last revision 2011-03-26 09:30 UTC by birken at gmail dot com)

Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2016-06-07 16:30 UTC]
Related to request #52129.
 [2018-04-08 15:49 UTC]
-Status: Open +Status: Suspended
 [2018-04-08 15:49 UTC]
Thanks for the patch!  Howver, adding yet more string functions to
the standard library is controversial, especially when the
respective functionality could easily be implemented in userland.
Therefore, this feature requires the RFC process[1].  Please go
ahead and start it!  For the time being, I'm suspending this

[1] <>
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Sun Oct 24 18:03:38 2021 UTC