Laravel Utilities

Perform Multiple String Replacements Simultaneously with Str::swap()

Punyapal Shah 1 min read
edit this tip
Use Str::swap() to perform atomic multi-pattern string replacements using key-value translation dictionaries.

When generating template notifications, substituting placeholders in email bodies, or mapping abbreviations, chaining multiple str_replace() calls can cause earlier replacements to inadvertently corrupt later ones.

Str::swap() performs atomic multi-string replacements in a single operation.

Basic Replacement Map

use Illuminate\Support\Str;

$template = "Hello :name, your order :order_id is currently :status.";

$output = Str::swap([
    ':name'     => 'Punyapal',
    ':order_id' => '#4820',
    ':status'   => 'Processing',
], $template);

// Output: "Hello Punyapal, your order #4820 is currently Processing."

Sanitizing Input Characters

$slug = Str::swap([
    '&' => 'and',
    '@' => 'at',
    '%' => 'percent',
], 'Design & Code @ 100%');

// Output: "Design and Code at 100percent"

Summary

  • Replaces multiple key-value pairs in a single atomic pass.
  • Prevents cascading replacement bugs caused by sequential str_replace() chains.
  • Available as a static method (Str::swap) and fluent string helper (str()->swap()).
Tags: Laravel Strings Templates Utilities
Share on X

// Found an issue or want to contribute a tip? github.com/MrPunyapal/tips