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

[8.x] Add a string helper to swap multiple keywords in a string. #40831

Merged
merged 6 commits into from
Feb 7, 2022
Merged

[8.x] Add a string helper to swap multiple keywords in a string. #40831

merged 6 commits into from
Feb 7, 2022

Conversation

amitmerchant1990
Copy link
Contributor

This tweet by Aaron Francis inspired me to open this PR.

Essentially, it adds a new string helper called Str::swap that lets you swap multiple keywords, that you can specify in form of an array, in a string. This can come in handy in certain scenarios and I think it would be pretty useful if it's available in the framework natively.

Here are some examples.

echo Str::swap([
    'PHP' => 'PHP 8',
    'awesome' => 'fantastic'
], 'PHP is awesome');

// outputs: 'PHP 8 is fantastic'

echo Str::swap([
    'ⓐⓑ' => 'baz',
], 'foo bar ⓐⓑ');

// outputs: 'foo bar baz'

I explained this in a little more detail in this article.

@amitmerchant1990 amitmerchant1990 changed the title Add a string helper to swap multiple keywords in a string. [8.x] Add a string helper to swap multiple keywords in a string. Feb 6, 2022
@mabdullahsari
Copy link
Contributor

What is different from strtr?

@aarondfrancis
Copy link
Contributor

@mabdullahsari I think it's a lot easier to read! 😂 Laravel has a lot of functions that help make native PHP more clear.

Also they are not functionally the same, as the implementation here (which I prefer) follow your maps order, whereas strtr re-orders by key length.

$subject = 'test';

$map = [
    'te' => 'be',
    'test' => 'example',
];

dump('swap: ' . Str::swap($map, $subject));
// "swap: best"
dump('strtr: ' . strtr($subject, $map));
// "strtr: example"


$map = [
    'test' => 'example',
    'te' => 'be',
];
dump('swap: ' . Str::swap($map, $subject));
// "swap: example"
dump('strtr: ' . strtr($subject, $map));
// "strtr: example"

@amitmerchant1990
Copy link
Contributor Author

amitmerchant1990 commented Feb 7, 2022

On top of @aarondfrancis' comment, I think it has a meaningful name from which you instantly get to know what it's intended to do unlike strtr.

@taylorotwell taylorotwell merged commit f21506e into laravel:8.x Feb 7, 2022
@amitmerchant1990 amitmerchant1990 deleted the feature/string-swap branch February 8, 2022 10:41
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