[10.x] Add charAt method to both Str and Stringable #46349
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What does this PR propose
This PR adds new
charAt
method to bothIlluminate\Support\Str
andIlluminate\Support\Stringable
.charAt
method allows to get a character by index from a multibyte string.If this PR is accepted, you can do the following:
It also supports negative indexes:
If index is greater then string length, or if negative index less then negative length, then
null
will be returned:Why it do so
Str provides a better way to work with strings in Laravel, because it always work with multibyte strings.
For now there is no way to simply get character by index if you work not only with latin characters.
Behavior I would like to discuss
Current implementation will return
null
if index is greater then string length (or if negative index less then negative string length).null
indicates that string does not contain character at that index. For me this behaviour seems to be more strict then returning empty string (''
). If you see more meaning in returning empty strings, please describe why.