Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

How to create template tokens

Hi all,

I'm working on creating a document collaboration web app with php, mysql, jqueryui. I've been trying to find a way to be able to replace tokens / variables I have inside of a template with the values entered in the form. Some people have recommended using preg_replace or preg_replace_callback but I'm just not sure.

Here's an example.

I have four form fields: Name, Company Name, Date and Total Amount.

I have created tokens or placeholders for these:

{{name}} {{company_name}} {{date}} {{total_amount}}

These tokens are inside of a WYSIWYG template below like this:

Customer Name: {{name}} Company Name: {{company_name}} Date: {{date}} Amount: {{total_amount}}

I would like those tokens to be updated based on the form input.

Does anyone have any recommendations?

2 Answers

Also, do you think this would be better done with a specific php framework or maybe even with Ruby on Rails?

Randy Hoyt
STAFF
Randy Hoyt
Treehouse Guest Teacher

Frameworks and libraries will often have robust ways to handle defining and using tokens like this. But if you have just a pre-defined list, you can easily do it yourself. The preg_replace should do the trick, or even something a little simpler like str_replace. I assume you'll be saving the text entered into the WYSIWG form somewhere like a database, and then you'll be loading that text into a string variable. Then you can perform the replacements like this:

$output = ... // load the text in the WYSIWYG into a string variable, however you do that
$name = ... // get the name from the form submission, however you do that
$output = str_replace( "{{name}}", $name, $output);

Does that help?