4

I have a string as:

$string = "My name is {name}. I live in {detail.country} and age is {detail.age}";

and I have an array like that and it will be always in that format.

$array = array(
   'name' => 'Jon',
   'detail' => array(
     'country' => 'India',
     'age' => '25'
  )
);

and the expected output should be like :

My name is Jon. I live in India and age is 25

So far I tried with the following method:

$string = str_replace(array('{name}','{detail.country}','{detail.age}'), array($array['name'],$array['detail']['country'],$array['detail']['age']));

But the thing is we can not use the plain text of string variable. It should be dynamic on the basis of the array keys.

1
  • You might consider using Twig. Commented Mar 8, 2019 at 15:44

4 Answers 4

3

You can use preg_replace_callback() for a dynamic replacement:

$string = preg_replace_callback('/{([\w.]+)}/', function($matches) use ($array) {
    $keys = explode('.', $matches[1]);
    $replacement = '';

    if (sizeof($keys) === 1) {
        $replacement = $array[$keys[0]];
    } else {
        $replacement = $array;

        foreach ($keys as $key) {
            $replacement = $replacement[$key];
        }
    }

    return $replacement;
}, $string);

It also exists preg_replace() but the above one allows matches processing.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use a foreach to achieve that :

foreach($array as $key=>$value)
{
  if(is_array($value))
  {
      foreach($value as $key2=>$value2)
      {
           $string = str_replace("{".$key.".".$key2."}",$value2,$string); 
      }
  }else{
      $string = str_replace("{".$key."}",$value,$string);
  }
}
print_r($string);

The above will only work with a depth of 2 in your array, you'll have to use recurcivity if you want something more dynamic than that.

Comments

2

Here's a recursive array handler: http://phpfiddle.org/main/code/e7ze-p2ap

<?php

function replaceArray($oldArray, $newArray = [], $theKey = null) {
    foreach($oldArray as $key => $value) {
        if(is_array($value)) {
            $newArray = array_merge($newArray, replaceArray($value, $newArray, $key));
        } else {
            if(!is_null($theKey)) $key = $theKey . "." . $key;
            $newArray["{" . $key . "}"] = $value;
        }
    }
    return $newArray;
}

$array = [
   'name' => 'Jon',
   'detail' => [
     'country' => 'India',
     'age' => '25'
  ]
];
$string = "My name is {name}. I live in {detail.country} and age is {detail.age}";

$array = replaceArray($array);

echo str_replace(array_keys($array), array_values($array), $string);

?>

Comments

-3

echo "my name is ".$array['name']." .I live in ".$array['detail']['countery']." and my age is ".$array['detail']['age'];

1 Comment

Not very dynamic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.