Adding filterByRegex method to Laravel Collections #55147
Answered
by
rodrigopedra
mohammadrasoulasghari
asked this question in
Ideas
-
Hi everyone! I'm considering contributing a new method to Laravel's Collection class called What it doesThe method would allow filtering collections using regular expressions in a clean, readable way: // Filter strings directly
$collection->filterByRegex('/^p/');
// Filter by a specific key
$users->filterByRegex('/@gmail\.com$/', 'email');
// Filter with dot notation for nested arrays
$data->filterByRegex('/PHP/', 'user.profile.bio');
// Filter with a callback
$products->filterByRegex('/2023/', fn($product) => $product->sku); Why I think it’s usefulWhile this can be done with the existing filter() method, filterByRegex would:
Questions
I’d appreciate your thoughts before submitting a PR. Thanks! |
Beta Was this translation helpful? Give feedback.
Answered by
rodrigopedra
Apr 18, 2025
Replies: 1 comment 10 replies
-
While it is possible using filter, that one uses a closure. I would opt for altering filter to accept a string that executes the regular expression. |
Beta Was this translation helpful? Give feedback.
10 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @mohammadrasoulasghari, I would have it as a separate function, as per your suggestion.
JavaScript takes both a string and a regular expression on some
String
methods (replace()
,match()
, ...), and more often than not I had to explain the difference of using each to new developers. I guess if there were different methods, it could be somehow easier to spot the difference.In JavaScript-land, one could argue those ambiguities don't happen, as regular expressions have their own delimiters, but in PHP, that is not the case.
I also think that the lesser a method does, its intent is clearer, and it is easier to test.
And, IMHO, the more execution paths a function has, the more prone to bug…