Search⌘ K
AI Features

Replacing a Key/Value Pair of Strings within a String

Explore how to use Laravel's swap helper method to replace key/value pairs within strings safely. Understand its advantages over traditional replace methods, especially in templating, to avoid unintended replacements and ensure reliable string manipulations in your applications.

We'll cover the following...

The swap helper methods

The swap helper method is another way to replace values in an existing string. The swap method accepts a key/value pair of string replacements as its first argument and the string to replace values as its second.

The behavior of the swap method is quite different from other string replacement methods you might have encountered.

PHP
<?php
/**
* Versions: Laravel 8, 9
*
* @return string
*/
public static function swap(
array $map,
string $subject
);

To highlight the behavior differences, we will create a simple canned email template function. We will first implement this function using the replace helper method. We will use the following email template across all the following ...