Home > Net >  How do i properly replace a placeholder text in PHP/Laravel and fallback to empty string if no data
How do i properly replace a placeholder text in PHP/Laravel and fallback to empty string if no data

Time:10-07

This is the text

Hello {first_name}, from {company}. This is your email address: {email}. Your application for {team} has been approved.

And i have these data for the placeholders. Notice that its missing first_name & team.

Expected result:

Hello, from contoso inc. This is your email address: [email protected]. Your application for has been approved.

Here's what i did so far.

Str::of($content)->replaceMatches('/\{([^}]*)\}/', function ($match) use ($placeholders) {
            return data_get($placeholders, $match[1]);
    });

Which produced

Hello , from contoso inc. This is your email address: [email protected]. Your application for has been approved.

Notice that there's space after hello and double space after for

CodePudding user response:

The code you provided is OK. But the format is not what you expect.

data_get will return a null value when data cannot be processed :

Format
Hello {first_name}, from {company}.
This is your email address: {email}.
Your application for {team} has been approved.
Result
Hello , from contoso inc.
This is your email address: [email protected].
Your application for  has been approved.

NULL won't change anything as you expect, because the spaces are in your format.

You can simply add squish to remove all extraneous white space, and use replace to correct the formatting of [SPACE], :

$text = Str::of($content)
    ->replaceMatches('/\{([^}]*)\}/', function ($match) use ($placeholders) {
        return data_get($placeholders, $match[1]);
    })
    ->replace(' ,', ',')
    ->squish();
Hello, from contoso inc.
This is your email address: [email protected].
Your application for has been approved.
  • Related