0

I am creating a function to parse text from a templating system, and add the corresponding values.

For example, the user might input hi [[first_name]] and the [[first_name]] part will be replaced with the actual first name.

Somehow, I parsed that and ended up with a text that looks like this:

hi $info['first_name']

The above is just as text though, what can I do to actually make $info['first_name'] be the value (I already have that array in there, but I am not sure how to convert string to PHP variable)

Thanks!

4
  • Please post the code where your variables you want inserted into the view are defined. Commented Nov 11, 2011 at 18:39
  • 2
    Why are you using a templating system at all? PHP itself is a templating engine, why add unnecessary overhead on top of it? Commented Nov 11, 2011 at 18:43
  • $info['first_name'] is the variable. Commented Nov 11, 2011 at 18:47
  • @NullUserExceptionఠ_ఠ I have been wondering the same thing :) The argument that's it's easier for designers to use random syntax opening first_name random syntax ending over <?= $first_name ?> doesn't really convince me. ok off-topic but this is killing me. Commented Nov 11, 2011 at 18:55

3 Answers 3

1

Use simple str_replace function:

$str = "hi [[first_name]]";
foreach (array_keys($info) as $key) {
    $str = str_replace("[[".$key."]]", $info[$key], $str);
}
echo $str;
Sign up to request clarification or add additional context in comments.

Comments

0
 str_replace("[[first_name]]", $info['first_name'], 'hi [[first_name]]');

You haven't share your code but you may print the variable name instead of its value.

Comments

0
<?php
$myTemplate = "hi [[first_name]], how are you this fine [[day_of_week]]?";

$myData = array(
  '[[first_name]]' => 'James'
  ,'[[day_of_week]]' => 'Friday'
);

echo str_replace(array_keys($myData), array_values($myData), $myTemplate);
?>

Comments

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.