I need to implement something like mail merge using PHP. Meaning, I will have a string containing special "merge tags" that will be replaced with certain values. For example:


The *|FIRST_NAME|* is what I'm calling a "merge tag", by the way. Of course, this can be implement using a simple str_replace. Or if I wanted to support ability to "escape" these merge tags (e.g. via a \, like \*|FIRST_NAME|*), then maybe use regex to find a merge tag not preceded by a \ -- and only merge those.

What is this "merge tag" concept called? Before I go on implementing my own solution, I want to see if a function or library already exist for what I need to do. I don't know what to google for, though.

Additionally, there is this "something else" I need to implement. Again, I do not know what it's called. It's a custom syntax that allows the construction of a string using "tokens" that represent multiple values. For example:

Hello ((world)|(planet))

The ((world)|(planet)) is what I'm calling "token". The example suggests that I can have the following strings:

  • Hello world
  • Hello planet

I need some sort of function to process strings with such tokens and return an array of all possible outputs. There should be support for unlimited tokens within the original string, as well as support for "nesting" these tokens, like:

(Hello ((world)|(planet)))|(Greetings ((cruel world)|(to you, dear sir.)))

That would produce:

  • Hello world
  • Hello planet
  • Greetings cruel world
  • Greetings to you, dear sir.

What is this "token" concept called? And is there a library or something already in existence that I can use for it?

By the way, in the two examples, the actual symbols used in the "merge tags" and the "tokens" are irrelevant.


What is this "merge tag" concept called?

How you're doing it is called string replacement.

What you're trying to do is called "fill in the blank".

There are other ways to do it. Here's one:

$email_body = "Dear $first_name.\n".

see example

That means your letter is in source. Your way of doing it makes sense if the letter is not in source but is simply a text file.

Your "something else" already has an answer on stackoverflow: create set of all possible matches for a given regex

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.