laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Add Str::removeSpaces #2495

Open honzahana opened 3 years ago

honzahana commented 3 years ago

Please add removeSpaces to Str helper and Fluent String. This is especially useful for sanitizing phone numbers and zip codes.

Str::macro('removeSpaces', function (string $value) {
    return preg_replace('/[\s]+/mu', '', $value);
});

Stringable::macro('removeSpaces', function () {
    return new Stringable(preg_replace('/[\s]+/mu', '', $this->value));
});

Regex based on: https://stackoverflow.com/a/58252825

Discussed here: https://laracasts.com/discuss/channels/laravel/extend-str-helper

danilopolani commented 3 years ago

You can just do Str::of('foo')->replaceMatches('/[\s]+/mu', ''), anyway I feel like opening a PR would be more effective

rimace commented 3 years ago

Some countries may type phone numbers and zip-codes as 012-345-6789. Wouldn't it be better to have a function like extractNumber() That removes everything except digits? I feel like that would be more general and fit your requirements.

honzahana commented 3 years ago

Extracting phone numbers was an example. It is also useful for removing spaces from VAT IDs, Company Registration Numbers (EU), postcodes, credit card numbers and so on.