Skip to content

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
@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.

4 participants