Skip to content

[7.x] Add split() to Stringable class#32713

Merged
taylorotwell merged 2 commits into
laravel:7.xfrom
tuarrep:patch-1
May 8, 2020
Merged

[7.x] Add split() to Stringable class#32713
taylorotwell merged 2 commits into
laravel:7.xfrom
tuarrep:patch-1

Conversation

@tuarrep

@tuarrep tuarrep commented May 7, 2020

Copy link
Copy Markdown

Add a split() method to Stringable as a proxy to preg_split() to allow splitting by regex in addition of explode()

Example

Str::of('hypertext language, programming')
    ->split('/[\s,]+/');

/*
Illuminate\Support\Collection {#3523
     all: [
       "hypertext",
       "language",
       "programming",
     ],
   }

*/

@GrahamCampbell

Copy link
Copy Markdown
Collaborator

I think you will need to first add this method to the Str class.

*/
public function split($pattern, $limit = -1, $flags = 0)
{
$keywords = preg_split($pattern, $this->value, $limit, $flags);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about error handling?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

preg_split returns false on failing

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, and then you hide the error? Fail doesn't mean no matches, it means that the pattern was invalid, but you hide this.

@tuarrep tuarrep May 7, 2020

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok get it! What's the recommended handling in this case? Removing the condition? Errors seem to be ignored for most methods
eg:

preg_match_all($pattern, $this->value, $matches);

@tuarrep

tuarrep commented May 7, 2020

Copy link
Copy Markdown
Author

I think you will need to first add this method to the Str class.

As it was similar to explode I've though it'll be sufficient to add this only to Stringable. But I can

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants