Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 8, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/Illuminate/Support/Stringable.php
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,25 @@ public function explode($delimiter, $limit = PHP_INT_MAX)
return collect(explode($delimiter, $this->value, $limit));
}

/**
* Split string by a regular expression.
*
* @param string $pattern
* @param int $limit
* @param int $flags
* @return \Illuminate\Support\Collection
*/
public function split($pattern, $limit = -1, $flags = 0)
{
$keywords = preg_split($pattern, $this->value, $limit, $flags);
Copy link
Member

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
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
Member

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.

Copy link
Author

@tuarrep tuarrep May 7, 2020

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);


if (! $keywords) {
return collect();
}

return collect($keywords);
}

/**
* Cap a string with a single instance of a given value.
*
Expand Down