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
.
- company : contoso inc
- name : john doe
- email: [email protected]
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.