0

I dont like to use a template engine in PHP. But i do like to assign {variable} to a PHP variable. How can i convert these variables to a php variable?

I tried to search on stackoverflow etc, nothing is what i mean.

Probally you will suggest use a TPL engine but that is not my question. What should be the right term for this 'function'. I just wanna learn for example with a good tutorial.

{username} links to $user->data()->username

3
  • 1
    Do you mean that you want to do yourself what a template engine does? Because a template engine does exactly what you are asking. But you want to write the logic yourself. Am I correct? You are asking how to replace {username} USING php? Or am I misunderstanding. Commented Mar 17, 2017 at 18:45
  • 1
    You need a combination of a parser together with a compiler. That together is called a template engine. Commented Mar 17, 2017 at 18:46
  • May be it can help you php.net/manual/en/function.extract.php Commented Mar 17, 2017 at 19:04

1 Answer 1

2

If you are looking to roll your own basic templating you can use str_replace

$string = 'Hello {username} Today is {fulldate}';
$search = ['{username}', '{fulldate}'];
$replace = [$user->data()->username, date(DATE_RFC850)];
$result = str_replace($search, $replace, $string);

It's basic and crude and can be full of gotchcas if you're not careful. Which is why using a template engine is highly recommended. They are more powerful and generally safer then rolling your own.

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

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.