Re: Can we make str_(starts|ends)_with variadic?
| From: | Christian Schneider | Date: | Wed, 11 Jun 2025 09:58:54 +0000 |
| Subject: | Re: Can we make str_(starts|ends)_with variadic? | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-127646@lists.php.net to get a copy of this message | ||
Am 10.06.2025 um 21:46 schrieb Hans Henrik Bergan <hans@loltek.net>:
> Can we make str_(starts|ends)_with variadic?
> ```
> if (str_starts_with($url, "http://",
> "https://")) {
> // url
> }
> if (str_ends_with($filename, ".pdf", ".doc", ".docx")) {
> // document
> }
> if(str_ends_with($str, ...$validExtensions){
> // valid extension
> }
> ```
Hmm, being old-fashioned I would probably do this with a regex:
str_starts_with($url, "http://", "https://") => preg_match('#^https?://#', $url)
str_ends_with($filename, ".pdf", ".doc",
".docx") => preg_match('#\.(pdf|doc|docx)$#', $filename)
str_ends_with($str, ...$validExtensions) => preg_match('#\.(' . implode('|',
array_map(fn($v) => preg_quote($v, '#'), $ validExtensions)) . ')$#', $str)
And even though the variadic versions could easily be implemented in user-land I see your point
about your version being clearer and less error-prone, even though my old brain is worried about a
hidden loop (but that's an implementation detail and can be avoided if one really wants to).
Another way of thinking about it would be
array_any($validExtensions, fn($ext) => str_ends_with($str, $ext))
which is quite concise as well and avoids reimplementing iteration for individual functions
separately.
Which leaves me +-0 on this,
- Chris