Skip to content
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

[10.x] Adds start and end string replacement helpers #48025

Merged
merged 2 commits into from Aug 23, 2023

Conversation

joedixon
Copy link
Contributor

I've run into this issue a couple of times recently where I need to trim or replace a value from the start or end of a string.

For example, let’s assume our string is /path/to/my/public/nested/public and I want to remove /public from the end of the string. I can do:

Str::replaceLast('/public', '', '/path/to/my/public/nested/public');

// /path/to/my/public/nested

This works fine until I pass a string which no longer has /public on the end and suddenly, the /public is removed from the middle of my string:

Str::replaceLast('/public', '', '/path/to/my/public/nested');

// /path/to/my/nested

Of course, I can get around this, but it feels kinda cumbersome:

if (Str::endsWith('/path/to/my/public/nested/public', '/public')) {
    Str::replaceLast('/public', '', '/path/to/my/public/nested');
}

// /path/to/my/public/nested

This PR combines this approach into four new string helpers

Str::replaceEnd('/public', '/private', '/path/to/my/public/nested/public');
// /path/to/my/public/nested/private

Str::replaceStart('/public', '/private', '/public/path/to/my/public/nested/public');
// /private/path/to/my/public/nested/public

Str::pruneEnd('/path/to/my/public/nested/public', '/public');
// /path/to/my/public/nested

Str::pruneStart('/public/path/to/my/public/nested/public', '/public');
// /path/to/my/public/nested/public

In each end method, the replacement is only carried out if the given value exists at the end of the string. It only replaces the last occurrence.

In each start method, the replacement is only carried out if the given value exists at the start of the string. It only replaces the first occurrence.

In both cases, the prune method wraps the replace counterpart as sugar to prevent the need to pass the empty string.

@joedixon joedixon closed this Aug 10, 2023
@joedixon joedixon reopened this Aug 23, 2023
@taylorotwell taylorotwell merged commit 38434a7 into 10.x Aug 23, 2023
20 of 21 checks passed
@taylorotwell taylorotwell deleted the feat/string-end-helpers branch August 23, 2023 19:45
@timacdonald
Copy link
Member

Love this.

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.

None yet

3 participants