0

I get string from eloquent like this :

Hi my name is {{ client_given_name }} and i live in {{ client_city }}.

and i have à Eloquent object like:

[
    "id" => 12
    "given_name" => "John"
    "family_name" => "DOE"
    "email" => "john.doe@protonmail.com"
    "phone_number" => null
    "city" => "Paris"
    "organization_id" => 5485
    "created_at" => "2022-07-28 09:29:09"
    "updated_at" => "2022-07-28 09:29:09"
]

I would like to detect the values between the braces and replace them with values from an Eloquent object. So that it corresponds to :

Hi my name is John and i live in Paris.

I tried this but the $client variable is not passed into the closure and it does not return what I am looking for.

$client = Client::find(1);
$replaced = Str::of($content)->replaceMatches('/\{{(.*?)}}/', function ($match) {
    if($match[1] === "client_name") {
        return $client->$match[1];
    }
});
GotExx
  • 117
  • 4
  • 17

1 Answers1

0

Following @user3783243 comment, I used use to get what I wanted.

$content = Str::of($content)->replaceMatches('/\{{(.*?)}}/', function ($match) use ($client) {

$value = trim($match[1]);
switch ($value) {
    case "searched_text":
        return $client->$value ?? '';
        break;
GotExx
  • 117
  • 4
  • 17