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" => "[email protected]"
    "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];
    }
});
1
  • 1
    I think you can use the use function, function ($match) use($client) Commented Jul 29, 2022 at 18:16

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.