Skip to content

[String] Replace at start / end of string #39192

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

Closed
apfelbox opened this issue Nov 27, 2020 · 7 comments
Closed

[String] Replace at start / end of string #39192

apfelbox opened this issue Nov 27, 2020 · 7 comments

Comments

@apfelbox
Copy link
Contributor

apfelbox commented Nov 27, 2020

Description

Hi, I would be great to have a method to replace strings only at the start/end of the string.

This is currently possible with

if ($path->startsWith($basePath))
{
    $path = $path->slice($basePath->length())->prepend("...");
}

but that is a common enough task to warrant a separate function for, imo.

Example

$baseDir = __DIR__;
$possiblyRelative = $path->replaceStart($baseDir, ".");

(names tbd)

@nicolas-grekas
Copy link
Member

Can't you use beforeLast(), after()?

@apfelbox
Copy link
Contributor Author

apfelbox commented Dec 9, 2020

@nicolas-grekas thank you for your response!

Can't you use beforeLast(), after()?

I don't think so (not sure I understand these methods with their edge cases correctly?)

To stay in my example:
If I understand it correctly, I can do a after() to get the relative path (or the full path, if after() didn't find a match). So I can correctly strip the $basePath.

However, in case the after() found something, I need to prepend it with a . and it doesn't seem that I have this info?

So iiuc I would need to do this:

$prefix = $path->startsWith($basePath) ? "." : "";
$path = $path->after($basePath)->prepend($prefix);

Which is arguably even less readable?

@carsonbot
Copy link

Thank you for this suggestion.
There has not been a lot of activity here for a while. Would you still like to see this feature?

@apfelbox
Copy link
Contributor Author

I would still like to see it, as I find the proposed solution highly confusing.

@carsonbot carsonbot removed the Stalled label Jun 10, 2021
@carsonbot
Copy link

Thank you for this suggestion.
There has not been a lot of activity here for a while. Would you still like to see this feature?

@apfelbox
Copy link
Contributor Author

@carsonbot unchanged, yes. 😊

@carsonbot carsonbot removed the Stalled label Dec 11, 2021
@nicolas-grekas
Copy link
Member

Solved by #43481:

use this:

u('file-image-0001.png')->trimPrefix('file-')->prepend('file-');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants